5

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?

1

3 Answers 3

11
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
Sign up to request clarification or add additional context in comments.

3 Comments

You should probably use identity comparison === in a prototype enhancement.
@Tomalak: Done, I suppose if you passed in an Array as the str argument, this would make a difference.
Your method is buggy. It fails if str.length === 0.
5

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

1 Comment

+1 I would store the this.length-suffix.length in a variable l and then return on one line: return l >= 0 && this.lastIndexOf(suffix) === l;
1

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)

2 Comments

Which browser did you test? "abc".substring(-1) doesn't work on Firefox
@BurnoLM I guess I was used to the way PHP does it, my update should work.

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.