如何检查字符串是否以JavaScript中的特定字符结束?

示例:我有一个字符串

var str = "mystring#";

我想知道字符串是否以#结尾。我怎么检查呢?

在JavaScript中有endsWith()方法吗? 我有一个解决方案,取字符串的长度,并得到最后一个字符,并检查它。

这是最好的办法还是还有别的办法?


当前回答

/#$/.test(str)

将在所有浏览器上工作,不需要猴子修补字符串,也不需要扫描整个字符串,因为lastIndexOf做的时候没有匹配。

如果你想匹配一个常量字符串,它可能包含正则表达式的特殊字符,比如'$',那么你可以使用以下方法:

function makeSuffixRegExp(suffix, caseInsensitive) {
  return new RegExp(
      String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
      caseInsensitive ? "i" : "");
}

然后你可以这样使用它

makeSuffixRegExp("a[complicated]*suffix*").test(str)

其他回答

if(typeof String.prototype.endsWith !== "function") {
    /**
     * String.prototype.endsWith
     * Check if given string locate at the end of current string
     * @param {string} substring substring to locate in the current string.
     * @param {number=} position end the endsWith check at that position
     * @return {boolean}
     *
     * @edition ECMA-262 6th Edition, 15.5.4.23
     */
    String.prototype.endsWith = function(substring, position) {
        substring = String(substring);

        var subLen = substring.length | 0;

        if( !subLen )return true;//Empty string

        var strLen = this.length;

        if( position === void 0 )position = strLen;
        else position = position | 0;

        if( position < 1 )return false;

        var fromIndex = (strLen < position ? strLen : position) - subLen;

        return (fromIndex >= 0 || subLen === -fromIndex)
            && (
                position === 0
                // if position not at the and of the string, we can optimise search substring
                //  by checking first symbol of substring exists in search position in current string
                || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
            )
            && this.indexOf(substring, fromIndex) === fromIndex
        ;
    };
}

好处:

这个版本不仅仅重用了indexOf。 在长弦上的最佳表现。这里有一个速度测试http://jsperf.com/starts-ends-with/4 完全兼容ecmascript规范。它通过了测试

7岁的帖子,但我不能理解前几篇帖子,因为它们很复杂。所以,我写了自己的解决方案:

function strEndsWith(str, endwith)
{
    var lastIndex = url.lastIndexOf(endsWith);
    var result = false;
    if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
    {
        result = true;
    }
    return result;
}

这个版本避免了创建子字符串,并且没有使用正则表达式(这里有些正则表达式可以工作;其他的则坏了):

String.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}

如果性能对您来说很重要,那么值得测试一下lastIndexOf是否比创建子字符串更快。(这可能取决于你使用的JS引擎…)在匹配的情况下,它可能会更快,当字符串很小的时候——但是当字符串很大的时候,它需要回顾整个事情,即使我们真的不关心:(

对于检查单个字符,查找长度然后使用charAt可能是最好的方法。

不幸的是没有。 If ("mystring#".substr(-1) === "#") {}

function check(str)
{
    var lastIndex = str.lastIndexOf('/');
    return (lastIndex != -1) && (lastIndex  == (str.length - 1));
}