views:

11847

answers:

11

How can I check if a string ends with a particular character in javascript? example I have a string say var str = "mystring#"; I want to know if that string str 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?

A: 

You can add one if you like:

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

alert("markmac".endsWith(“mac”));

Should do it...

Mark
Doesn't that assume that the string doesn't use any regular expression elements itself?
Jon Skeet
For example, this prints false: alert("ab[x]".endsWith("[x]"));
Jon Skeet
Moreover, this fails for "30$".endsWith("$"), "123".endsWith(")"), etc.
Panos
this failed when "mystring$".endsWith("$"). it gave false
Bobby Kumar
Should be “return this.substring(this.length-str.length)==str”. Be careful when writing prototypes, if you are using non-standard names or broken implementations like this, you can easily confuse other code on the page. A standalone function is more reliable in mixed-code environments.
bobince
+8  A: 
  1. Unfortunately not.
  2. if( "mystring#".substr(-1) === "#" ) {}
digitala
This wouldn't work in Internet Explorer though.
Anthony
+2  A: 
if( ("mystring#").substr(-1,1) == '#' )

-- Or --

if( ("mystring#").match(/#$/) )
duckyflip
A: 

There's nothing that a good piece of regexp and some prototype extension won't fix.

Include this in your script:

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

After you include it you can use endsWith on any String.

Bogdan
I was going to suggest something that wrapped .lastIndexOf(str) but your regex is much better. nice work!
scunliffe
As commented to Mark: this doesn't work if the string already includes regular expression elements. Try "ab[x]".endsWith("[x]")
Jon Skeet
A: 

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.

Bobby Kumar
+8  A: 

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.

Jon Skeet
If this.lastIndexOf() returns -1, you can hit cases where it returns true dependong on this.length and str.length. Add a test that lastIndexOf() != -1.
ebruchez
Good catch, thanks.
Jon Skeet
Downvoters: Care to explain why you've downvoted?
Jon Skeet
Why is the regex method broken?
izb
@izb: The answers which are older than mine which try to use `str+"$"` as a regex are broken, as they may not be valid regexes.
Jon Skeet
+2  A: 
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
jon skeet smackdown!
nickf
You have earned the “Found a mistake in a Jon Skeet answer” badge. See your profile for details.
bobince
+24  A: 
/#$/.test(str)

will work on all browsers, doesn't require monkey patching String, and doesn't require scanning the entire string as lastIndexOf does.

Mike Samuel
This is nice and simple if you're checking for a constant substring.
Warren Blanchet
+6  A: 

Come on, this is the correct endsWith implementation:

String.prototype.endsWidth = 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.

Oskar Liljeblad
+5  A: 

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 simplify 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;
}
chakrit
A: 
function check(str)
{
    var lastIndex = str.lastIndexOf('/');
    return (lastIndex != -1) && (lastIndex  == (str.length - 1));
}
manish