代码之家  ›  专栏  ›  技术社区  ›  Jon Erickson

javascript或jquery字符串以实用函数结尾

  •  73
  • Jon Erickson  · 技术社区  · 15 年前

    找出字符串是否以某个值结尾的最简单方法是什么?

    8 回复  |  直到 8 年前
        1
  •  151
  •   cloudhead    15 年前

    可以使用regexps,如下所示:

    str.match(/value$/)
    

    如果字符串末尾有'value'($),则返回true。

        2
  •  38
  •   Luca Matteis    15 年前

    从原型中被盗:

    String.prototype.endsWith = function(pattern) {
        var d = this.length - pattern.length;
        return d >= 0 && this.lastIndexOf(pattern) === d;
    };
    
    'slaughter'.endsWith('laughter');
    // -> true
    
        3
  •  9
  •   Chetan S    15 年前

    正则表达式

    "Hello world".match(/world$/)
    
        4
  •  5
  •   theJerm    12 年前

    我不太擅长比赛方法,但这很有效:

    如果你有一个字符串,“这是我的字符串”,想看看它是否以句点结尾,那么就这样做:

    var myString = "This is my string.";
    var stringCheck = ".";
    var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
    alert(foundIt);
    

    可以将变量string check更改为要检查的任何字符串。最好还是把它放到你自己的函数中,比如:

    function DoesStringEndWith(myString, stringCheck)
    {
        var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
        return foundIt;
    }
    
        5
  •  4
  •   John Henckel    8 年前

    你可以做到 'hello world'.slice(-5)==='world' . 适用于所有浏览器。比regex快得多。

        6
  •  2
  •   Mr. Goferito    8 年前

    ES6直接支持这一点:

    'this is dog'.endsWith('dog')  //true
    
        7
  •  1
  •   georgephillips    12 年前

    我只是在扩展@luca matteis发布的内容,但是为了解决注释中指出的问题,应该包装代码,以确保不会覆盖本机实现。

    if ( !String.prototype.endsWith ) {  
        String.prototype.endsWith = function(pattern) {
            var d = this.length - pattern.length;
            return d >= 0 && this.lastIndexOf(pattern) === d;
        };
    }
    

    这是中指出的array.prototype.foreach方法的建议方法 the mozilla developer network

        8
  •  0
  •   Jaime Hablutzel    14 年前

    您可以始终原型化字符串类,这将起作用:

    string.prototype.endswith=函数(str) 返回(this.match(str+“$”)==str)

    在中可以找到字符串类的其他相关扩展名。 http://www.tek-tips.com/faqs.cfm?fid=6620