76

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

1

8 Answers 8

159

you could use Regexps, like this:

str.match(/value$/)

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

Sign up to request clarification or add additional context in comments.

4 Comments

Fail test: value="test[a-z]". Otherwise: 'test[a-z]'.match(/[a-z]$/) is return "null"
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)
match() does not return a boolean. 'foobar'.match(/bar$/) returns ["bar"]
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) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
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

4 Comments

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.
Why shouldn't you do it? Or you just don't do it because Crockford said it?
You shouldn't do it as it isn't guaranteed to work in all implementations of JS: the ECMAScript Compact Profile spec (ECMA-327: 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.
If someone doesn't want to modify String they can turn it into a standalone function very easily.
9

Regular expressions

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

Comments

6

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;
}

1 Comment

Really nice, @theJerm. This worked for me in a variety of situations whereas .match didn't always.
5

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

Comments

4

ES6 supports this directly:

'this is dog'.endsWith('dog')  //true

2 Comments

This will be useful once no-one is using IE11 or below any more.
Yup, but for that you have babel.
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

Comments

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

2 Comments

This will fail if str contains special regexp characters, for example "[ssss]".
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.