Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a "EndsWith" on a string?

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?

like image 590
BrunoLM Avatar asked Dec 05 '22 01:12

BrunoLM


2 Answers

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
like image 183
Andy E Avatar answered Dec 07 '22 14:12

Andy E


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
like image 24
Adam Avatar answered Dec 07 '22 14:12

Adam