[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?

  1. Is there a endsWith() method in JavaScript?

  2. 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?

This question is related to javascript string ends-with

The answer is


return this.lastIndexOf(str) + str.length == this.length;

does not work in the case where original string length is one less than search string length and the search string is not found:

lastIndexOf returns -1, then you add search string length and you are left with the original string's length.

A possible fix is

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length

Just another quick alternative that worked like a charm for me, using regex:

// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null

if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

or as a standalone function

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}

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

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

Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js. Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js In general, this is a nice language-level library: groundjs You can also take a look at lodash


After all those long tally of answers, i found this piece of code simple and easy to understand!

function end(str, target) {
  return str.substr(-target.length) == target;
}

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

@chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as @mlunoe pointed out. Using underscore.string, the code would be:

function endsWithHash(str) {
  return _.str.endsWith(str, '#');
}

all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.

I found a better solution than mine. Thanks every one.


if(typeof String.prototype.endsWith !== "function") {
    /**
     * String.prototype.endsWith
     * Check if given string locate at the end of current string
     * @param {string} substring substring to locate in the current string.
     * @param {number=} position end the endsWith check at that position
     * @return {boolean}
     *
     * @edition ECMA-262 6th Edition, 15.5.4.23
     */
    String.prototype.endsWith = function(substring, position) {
        substring = String(substring);

        var subLen = substring.length | 0;

        if( !subLen )return true;//Empty string

        var strLen = this.length;

        if( position === void 0 )position = strLen;
        else position = position | 0;

        if( position < 1 )return false;

        var fromIndex = (strLen < position ? strLen : position) - subLen;

        return (fromIndex >= 0 || subLen === -fromIndex)
            && (
                position === 0
                // if position not at the and of the string, we can optimise search substring
                //  by checking first symbol of substring exists in search position in current string
                || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
            )
            && this.indexOf(substring, fromIndex) === fromIndex
        ;
    };
}

Benefits:

  • This version is not just re-using indexOf.
  • Greatest performance on long strings. Here is a speed test http://jsperf.com/starts-ends-with/4
  • Fully compatible with ecmascript specification. It passes the tests

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.


If you're using lodash:

_.endsWith('abc', 'c'); // true

If not using lodash, you can borrow from its source.


all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.

I found a better solution than mine. Thanks every one.


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

I just learned about this string library:

http://stringjs.com/

Include the js file and then use the S variable like this:

S('hi there').endsWith('hi there')

It can also be used in NodeJS by installing it:

npm install string

Then requiring it as the S variable:

var S = require('string');

The web page also has links to alternate string libraries, if this one doesn't take your fancy.


/#$/.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)

This is the implementation of endsWith:

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

This builds on @charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.

if (typeof String.prototype.endsWith === 'undefined') {
    String.prototype.endsWith = function(suffix) {
        if (typeof suffix === 'String') {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        }else if(suffix instanceof Array){
            return _.find(suffix, function(value){
                console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                return this.indexOf(value, this.length - value.length) !== -1;
            }, this);
        }
    };
}

This requires underscorejs - but can probably be adjusted to remove the underscore dependency.


if( ("mystring#").substr(-1,1) == '#' )

-- Or --

if( ("mystring#").match(/#$/) )

This builds on @charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.

if (typeof String.prototype.endsWith === 'undefined') {
    String.prototype.endsWith = function(suffix) {
        if (typeof suffix === 'String') {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        }else if(suffix instanceof Array){
            return _.find(suffix, function(value){
                console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                return this.indexOf(value, this.length - value.length) !== -1;
            }, this);
        }
    };
}

This requires underscorejs - but can probably be adjusted to remove the underscore dependency.


This is the implementation of endsWith : String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }


This is the implementation of endsWith:

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

String.prototype.endWith = function (a) {
    var isExp = a.constructor.name === "RegExp",
    val = this;
    if (isExp === false) {
        a = escape(a);
        val = escape(val);
    } else
        a = a.toString().replace(/(^\/)|(\/$)/g, "");
    return eval("/" + a + "$/.test(val)");
}

// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));

if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

or as a standalone function

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}

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.


For coffeescript

String::endsWith = (suffix) ->
  -1 != @indexOf suffix, @length - suffix.length

function check(str)
{
    var lastIndex = str.lastIndexOf('/');
    return (lastIndex != -1) && (lastIndex  == (str.length - 1));
}

I don't know about you, but:

var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!

Why regular expressions? Why messing with the prototype? substr? c'mon...


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.


From developer.mozilla.org String.prototype.endsWith()

Summary

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.

Syntax

str.endsWith(searchString [, position]);

Parameters

  • searchString : The characters to be searched for at the end of this string.

  • position : Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.

Description

This method lets you determine whether or not a string ends with another string.

Examples

var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

Specifications

ECMAScript Language Specification 6th Edition (ECMA-262)

Browser compatibility

Browser compatibility


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

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

7 years old post, but I was not able to understand top few posts, because they are complex. So, I wrote my own solution:

function strEndsWith(str, endwith)
{
    var lastIndex = url.lastIndexOf(endsWith);
    var result = false;
    if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
    {
        result = true;
    }
    return result;
}

function check(str)
{
    var lastIndex = str.lastIndexOf('/');
    return (lastIndex != -1) && (lastIndex  == (str.length - 1));
}

I just learned about this string library:

http://stringjs.com/

Include the js file and then use the S variable like this:

S('hi there').endsWith('hi there')

It can also be used in NodeJS by installing it:

npm install string

Then requiring it as the S variable:

var S = require('string');

The web page also has links to alternate string libraries, if this one doesn't take your fancy.


String.prototype.endWith = function (a) {
    var isExp = a.constructor.name === "RegExp",
    val = this;
    if (isExp === false) {
        a = escape(a);
        val = escape(val);
    } else
        a = a.toString().replace(/(^\/)|(\/$)/g, "");
    return eval("/" + a + "$/.test(val)");
}

// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));

if( ("mystring#").substr(-1,1) == '#' )

-- Or --

if( ("mystring#").match(/#$/) )

A way to future proof and/or prevent overwriting of existing prototype would be test check to see if it has already been added to the String prototype. Here's my take on the non-regex highly rated version.

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

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.


all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.

I found a better solution than mine. Thanks every one.


So many things for such a small problem, just use this Regular Expression

_x000D_
_x000D_
var str = "mystring#";_x000D_
var regex = /^.*#$/_x000D_
_x000D_
if (regex.test(str)){_x000D_
  //if it has a trailing '#'_x000D_
}
_x000D_
_x000D_
_x000D_


if(typeof String.prototype.endsWith !== "function") {
    /**
     * String.prototype.endsWith
     * Check if given string locate at the end of current string
     * @param {string} substring substring to locate in the current string.
     * @param {number=} position end the endsWith check at that position
     * @return {boolean}
     *
     * @edition ECMA-262 6th Edition, 15.5.4.23
     */
    String.prototype.endsWith = function(substring, position) {
        substring = String(substring);

        var subLen = substring.length | 0;

        if( !subLen )return true;//Empty string

        var strLen = this.length;

        if( position === void 0 )position = strLen;
        else position = position | 0;

        if( position < 1 )return false;

        var fromIndex = (strLen < position ? strLen : position) - subLen;

        return (fromIndex >= 0 || subLen === -fromIndex)
            && (
                position === 0
                // if position not at the and of the string, we can optimise search substring
                //  by checking first symbol of substring exists in search position in current string
                || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
            )
            && this.indexOf(substring, fromIndex) === fromIndex
        ;
    };
}

Benefits:

  • This version is not just re-using indexOf.
  • Greatest performance on long strings. Here is a speed test http://jsperf.com/starts-ends-with/4
  • Fully compatible with ecmascript specification. It passes the tests

This is the implementation of endsWith : String.prototype.endsWith = function (str) { return this.length >= str.length && this.substr(this.length - str.length) == str; }


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

all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.

I found a better solution than mine. Thanks every one.


If you're using lodash:

_.endsWith('abc', 'c'); // true

If not using lodash, you can borrow from its source.


String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

I hope this helps

var myStr = “  Earth is a beautiful planet  ”;
var myStr2 = myStr.trim();  
//==“Earth is a beautiful planet”;

if (myStr2.startsWith(“Earth”)) // returns TRUE

if (myStr2.endsWith(“planet”)) // returns TRUE

if (myStr.startsWith(“Earth”)) 
// returns FALSE due to the leading spaces…

if (myStr.endsWith(“planet”)) 
// returns FALSE due to trailing spaces…

the traditional way

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

function strEndsWith(str, suffix) {
    return str.match(suffix+"$")==suffix;
}

@chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as @mlunoe pointed out. Using underscore.string, the code would be:

function endsWithHash(str) {
  return _.str.endsWith(str, '#');
}

From developer.mozilla.org String.prototype.endsWith()

Summary

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.

Syntax

str.endsWith(searchString [, position]);

Parameters

  • searchString : The characters to be searched for at the end of this string.

  • position : Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.

Description

This method lets you determine whether or not a string ends with another string.

Examples

var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

Specifications

ECMAScript Language Specification 6th Edition (ECMA-262)

Browser compatibility

Browser compatibility


if( ("mystring#").substr(-1,1) == '#' )

-- Or --

if( ("mystring#").match(/#$/) )

After all those long tally of answers, i found this piece of code simple and easy to understand!

function end(str, target) {
  return str.substr(-target.length) == target;
}

Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.

'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)

Refer it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.


String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

I hope this helps

var myStr = “  Earth is a beautiful planet  ”;
var myStr2 = myStr.trim();  
//==“Earth is a beautiful planet”;

if (myStr2.startsWith(“Earth”)) // returns TRUE

if (myStr2.endsWith(“planet”)) // returns TRUE

if (myStr.startsWith(“Earth”)) 
// returns FALSE due to the leading spaces…

if (myStr.endsWith(“planet”)) 
// returns FALSE due to trailing spaces…

the traditional way

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

function strEndsWith(str, suffix) {
    return str.match(suffix+"$")==suffix;
}

if( ("mystring#").substr(-1,1) == '#' )

-- Or --

if( ("mystring#").match(/#$/) )

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

I don't know about you, but:

var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!

Why regular expressions? Why messing with the prototype? substr? c'mon...


So many things for such a small problem, just use this Regular Expression

_x000D_
_x000D_
var str = "mystring#";_x000D_
var regex = /^.*#$/_x000D_
_x000D_
if (regex.test(str)){_x000D_
  //if it has a trailing '#'_x000D_
}
_x000D_
_x000D_
_x000D_


Just another quick alternative that worked like a charm for me, using regex:

// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null

return this.lastIndexOf(str) + str.length == this.length;

does not work in the case where original string length is one less than search string length and the search string is not found:

lastIndexOf returns -1, then you add search string length and you are left with the original string's length.

A possible fix is

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length

function strEndsWith(str,suffix) {
  var reguex= new RegExp(suffix+'$');

  if (str.match(reguex)!=null)
      return true;

  return false;
}

For coffeescript

String::endsWith = (suffix) ->
  -1 != @indexOf suffix, @length - suffix.length

A way to future proof and/or prevent overwriting of existing prototype would be test check to see if it has already been added to the String prototype. Here's my take on the non-regex highly rated version.

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

Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js. Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js In general, this is a nice language-level library: groundjs You can also take a look at lodash


function strEndsWith(str,suffix) {
  var reguex= new RegExp(suffix+'$');

  if (str.match(reguex)!=null)
      return true;

  return false;
}

/#$/.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)

Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.

'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)

Refer it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.


7 years old post, but I was not able to understand top few posts, because they are complex. So, I wrote my own solution:

function strEndsWith(str, endwith)
{
    var lastIndex = url.lastIndexOf(endsWith);
    var result = false;
    if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
    {
        result = true;
    }
    return result;
}

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.