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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With