How to implement "EndsWith" in a string?

I have a line

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

I want to check if another line ends with s1

So, if I send these lines, it should 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?

+4
source share
3 answers
 if (str.slice(-s1.length) == s1) { } 

Or, less dynamic and more literal:

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

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

slice () - MDC

Adding this to the prototype string is easy:

 String.prototype.endsWith = function (str) { return this.slice(-str.length) === str; } alert("w,w,a,$,b,c".endsWith(s1)); // -> true 
+10
source

This will add the Java-like endWith method to String:

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

Then you can:

 "w,w,a,$,b,c".endsWith(s1) //true 
+5
source

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

Like this:

 if (s2.substring(s2.length - s1.length) == s1) 
+1
source

All Articles