76

what is the easiest way to figure out if a string ends with a certain value?

Jon Erickson
  • 112,242
  • 44
  • 136
  • 174
  • 3
    See also the second answer of this question: http://stackoverflow.com/questions/280634/endswith-in-javascript – Baldrick Sep 02 '12 at 12:25

8 Answers8

156

you could use Regexps, like this:

str.match(/value$/)

which would return true if the string has 'value' at the end of it ($).

cloudhead
  • 15,253
  • 6
  • 42
  • 37
  • 1
    Fail test: value="test[a-z]". Otherwise: 'test[a-z]'.match(/[a-z]$/) is return "null" – gmunkhbaatarmn Mar 29 '12 at 03:42
  • I don't normally grab the regex tool out of my bag first, but this beats all the alternatives (String#endsWith is supported natively only in firefox, and extending / using 3rd party js is a bit overkill) – diclophis Oct 09 '13 at 18:45
  • 2
    match() does not return a boolean. 'foobar'.match(/bar$/) returns ["bar"] – Jonathan.Brink Feb 10 '15 at 13:58
  • 2
    RegEx Search() instead of Match() would be a better option if we just want a boolean result. Search() will return -1 if there is no found. if(str.search(/value$/) != -1) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search – mitaka Oct 04 '16 at 13:20
40

Stolen from prototypejs:

String.prototype.endsWith = function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
};

'slaughter'.endsWith('laughter');
// -> true
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
  • 5
    Some people believe that modifying the prototype of a core class is something that you shouldn't do - Crockford refers to this as "global abatement" in his book JavaScript: The Good Parts. – Walter Rumsby Jul 07 '09 at 22:36
  • 4
    Why shouldn't you do it? Or you just don't do it because Crockford said it? – Luca Matteis Jul 07 '09 at 22:41
  • 11
    You shouldn't do it as it isn't guaranteed to work in all implementations of JS: the ECMAScript Compact Profile spec (ECMA-327: http://www.ecma-international.org/publications/standards/Ecma-327.htm) specifies that "Compact" implementations (e.g. on handheld devices such as phones) need not support it (see section 5.2). Even if you aren't bothered by that, it's quite possible that it will break newer versions of JS: for example, anybody who has in the past deployed code that adds a "forEach" method to Array.prototype is now breaking the native implementation in recent versions of Firefox. – NickFitz Jul 08 '09 at 11:05
  • 3
    If someone doesn't want to modify String they can turn it into a standalone function very easily. – studgeek Feb 25 '11 at 01:47
9

Regular expressions

"Hello world".match(/world$/)
Chetan S
  • 23,637
  • 2
  • 63
  • 78
5

I had no luck with the match approach, but this worked:

If you have the string, "This is my string." and wanted to see if it ends with a period, do this:

var myString = "This is my string.";
var stringCheck = ".";
var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
alert(foundIt);

You can change the variable stringCheck to be any string to check for. Better still would be to throw this in your own function like this:

function DoesStringEndWith(myString, stringCheck)
{
    var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
    return foundIt;
}
theJerm
  • 4,482
  • 2
  • 30
  • 23
  • 1
    Really nice, @theJerm. This worked for me in a variety of situations whereas .match didn't always. – Nathan Jun 04 '16 at 02:42
5

You can do 'hello world'.slice(-5)==='world'. Works in all browsers. Much faster than regex.

John Henckel
  • 10,274
  • 3
  • 79
  • 79
3

ES6 supports this directly:

'this is dog'.endsWith('dog')  //true
Mr. Goferito
  • 6,391
  • 4
  • 26
  • 27
1

I am just expanding on what @luca-matteis has posted but to solve the issues pointed out in the comments the code should be wrapped to make sure you are not overwriting a native implementation.

if ( !String.prototype.endsWith ) {  
    String.prototype.endsWith = function(pattern) {
        var d = this.length - pattern.length;
        return d >= 0 && this.lastIndexOf(pattern) === d;
    };
}

This is the suggested method for the Array.prototype.forEach method pointed out in the mozilla developer network

georgephillips
  • 3,540
  • 4
  • 23
  • 30
0

You can always prototype String class, this will work:

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

You can find other related extensions for String class in http://www.tek-tips.com/faqs.cfm?fid=6620

Jaime Hablutzel
  • 6,117
  • 5
  • 40
  • 57
  • 2
    This will fail if str contains special regexp characters, for example "[ssss]". – studgeek Feb 25 '11 at 01:47
  • This also fails because `match` returns an array. It would need to be `this.match(str+"$")[0]===str` (and that could fail if `match` doesn't find anything - didn't actually false-test this one). – TLS Apr 17 '18 at 16:37