endsWith in JavaScript

endsWith in JavaScript

How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
var str = “mystring#”;

I want to know if that string is ending with #. How can I check it?

Is there a endsWith() method in JavaScript?
One solution I have is take the length of the string and get the last character and check it.

Is this the best way or there is any other way?

Solutions/Answers:

Solution 1:

UPDATE (Nov 24th, 2015):

This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:


ORIGINAL ANSWER:

I know this is a year old question… but I need this too and I need it to work cross-browser so… combining everyone’s answer and comments and simplifying it a bit:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
  • Doesn’t create a substring
  • Uses native indexOf function for fastest results
  • Skip unnecessary comparisons using the second parameter of indexOf to skip ahead
  • Works in Internet Explorer
  • NO Regex complications

Also, if you don’t like stuffing things in native data structure’s prototypes, here’s a standalone version:

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

EDIT: As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a typeof check like so:

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

Solution 2:

/#$/.test(str)

will work on all browsers, doesn’t require monkey patching String, and doesn’t require scanning the entire string as lastIndexOf does when there is no match.

If you want to match a constant string that might contain regular expression special characters, such as '$', then you can use the following:

function makeSuffixRegExp(suffix, caseInsensitive) {
  return new RegExp(
      String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
      caseInsensitive ? "i" : "");
}

and then you can use it like this

makeSuffixRegExp("a[complicated]*suffix*").test(str)

Solution 3:

  1. Unfortunately not.
  2. if( "mystring#".substr(-1) === "#" ) {}

Solution 4:

Come on, this is the correct endsWith implementation:

String.prototype.endsWith = function (s) {
  return this.length >= s.length && this.substr(this.length - s.length) == s;
}

using lastIndexOf just creates unnecessary CPU loops if there is no match.

Solution 5:

This version avoids creating a substring, and doesn’t use regular expressions (some regex answers here will work; others are broken):

String.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}

If performance is important to you, it would be worth testing whether lastIndexOf is actually faster than creating a substring or not. (It may well depend on the JS engine you’re using…) It may well be faster in the matching case, and when the string is small – but when the string is huge it needs to look back through the whole thing even though we don’t really care 🙁

For checking a single character, finding the length and then using charAt is probably the best way.

Solution 6:

Didn’t see apporach with slice method. So i’m just leave it here:

function endsWith(str, suffix) {
    return str.slice(-suffix.length) === suffix
}