views:

114

answers:

3

I have a string

var s1 = "a,$,b,c";

I want to check if another string ends with s1

So if I send these strings it has to return true

w,w,a,$,b,c
^,^,^,$,@,#,%,$,$,a,$,b,c
a,w,e,q,r,f,z,x,c,v,z,$,W,a,$,b,c

And for these false

a,$,b,c,F,W
a,$,b,c,W
a,$,b,c,$,^,\,/

How can I check it?

+7  A: 
if (str.slice(-s1.length) == s1) { 
}

Or, less dynamically and more literally:

if (str.slice(-7) == s1) { 
}

Using a negative offset for slice() sets the starting point from the end of the string, minus the negative start - in this case, 7 characters (or s1.length) from the end.

slice() - MDC

Adding this to the string prototype is easy:

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

alert("w,w,a,$,b,c".endsWith(s1));
// -> true
Andy E
You should probably use identity comparison `===` in a prototype enhancement.
Tomalak
@Tomalak: Done, I suppose if you passed in an Array as the str argument, this would make a difference.
Andy E
+1  A: 

Get the length of the string s1, then get the substring of last digits of the test string and see if they are the same.

Like this:

if (s2.substring(s2.length - s1.length) == s1)
John Isaacks
Which browser did you test? `"abc".substring(-1)` doesn't work on Firefox
BrunoLM
@BurnoLM I guess I was used to the way PHP does it, my update should work.
John Isaacks
+5  A: 

This will add a Java-like endsWith method to String:

String.prototype.endsWith = function(suffix) { 
   if (this.length < suffix.length) 
      return false; 
   return this.lastIndexOf(suffix) === this.length - suffix.length; 
} 

You can then do:

"w,w,a,$,b,c".endsWith(s1) //true
Adam
+1 I would store the `this.length-suffix.length` in a variable `l` and then return on one line: `return l >= 0 `
Tomalak