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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

这是另一个对我来说很有魅力的快速替代方法,使用正则表达式:

// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null

其他回答

/#$/.test(str)

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

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

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

然后你可以这样使用它

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

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

对于coffeescript

String::endsWith = (suffix) ->
  -1 != @indexOf suffix, @length - suffix.length

这建立在@charkit的接受答案上,允许字符串数组或字符串作为参数传入。

if (typeof String.prototype.endsWith === 'undefined') {
    String.prototype.endsWith = function(suffix) {
        if (typeof suffix === 'String') {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        }else if(suffix instanceof Array){
            return _.find(suffix, function(value){
                console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                return this.indexOf(value, this.length - value.length) !== -1;
            }, this);
        }
    };
}

这需要下划线-但是可以调整以删除下划线依赖项。

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

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