首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript endWith()

JavaScript endWith()
EN

Stack Overflow用户
提问于 2010-05-08 00:09:05
回答 4查看 1K关注 0票数 0

我在运行以下代码时遇到了问题

if(str.endsWith('+')
{
   alert("ends in plus sign")
}

如何转义加号?我试过/\ +/,但它不起作用。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-05-08 00:12:26

JavaScript中没有endsWith方法,因此改用:

if (str.substr(-1) === "+") {
  alert("ends in plus sign")
}
票数 3
EN

Stack Overflow用户

发布于 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")) {
    // ...
}
票数 3
EN

Stack Overflow用户

发布于 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。字符串以数字和(可能的)冒号结尾

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2789973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档