我在运行以下代码时遇到了问题
if(str.endsWith('+')
{
alert("ends in plus sign")
}
如何转义加号?我试过/\ +/,但它不起作用。
发布于 2010-05-08 00:12:26
JavaScript中没有endsWith
方法,因此改用:
if (str.substr(-1) === "+") {
alert("ends in plus sign")
}
发布于 2010-05-08 00:18:16
Javascript字符串类型没有endsWith
函数,但是如果你愿意,你可以给它一个:
if (!String.prototype.endsWith) {
(function() {
String.prototype.endsWith = String_endsWith;
function String_endsWith(sub) {
return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
}
})();
}
或者,如果您不介意未命名的函数:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(sub) {
return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
};
}
无论哪种方式,您都可以这样做:
if ("foo".endsWith("oo")) {
// ...
}
发布于 2010-05-08 01:45:39
String.prototype.endswith= function(c){
if(!c) return this.charAt(this.length - 1);
else{
if(typeof c== "string") c= RegExp(c + "$");
return c.test(this);
}
}
var s=‘告诉我更多:’,s2=‘告诉我关于第二部分:’;
s.endsWith() //返回':';
s.endsWIth(':') //返回true,最后一个字符为':';
s2.endsWIth(/\d:?/) //返回true。字符串以数字和(可能的)冒号结尾
https://stackoverflow.com/questions/2789973
复制相似问题