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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

一种未来证明和/或防止覆盖现有原型的方法是测试检查它是否已经添加到String原型中。以下是我对非正则表达式高评级版本的看法。

if (typeof String.endsWith !== 'function') {
    String.prototype.endsWith = function (suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

其他回答

if( ("mystring#").substr(-1,1) == '#' )

——或者——

if( ("mystring#").match(/#$/) )

我不知道你怎么想,但是:

var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!

为什么是正则表达式?为什么要破坏原型?字符串的子串吗?来吧……

如果你正在使用lodash:

_.endsWith('abc', 'c'); // true

如果不使用lodash,可以从它的源代码中借用。

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规范。它通过了测试

我刚刚了解了这个字符串库:

http://stringjs.com/

包括js文件,然后像这样使用S变量:

S('hi there').endsWith('hi there')

它也可以通过安装在NodeJS中使用:

npm install string

然后需要它作为S变量:

var S = require('string');

这个网页还提供了其他字符串库的链接,如果你不喜欢这个库的话。