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?


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

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)
链接地址: http://www.djcxy.com/p/83900.html

上一篇: 确认字符串的结束(变化结束长度)

下一篇: 如何在字符串上实现“EndsWith”?