JavaScript or jQuery string ends with utility function

Viewed 78880

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

8 Answers

you could use Regexps, like this:

str.match(/value$/)

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

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

Regular expressions

"Hello world".match(/world$/)
Related