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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

这建立在@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.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}

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

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

来吧,这是正确的结局与实现:

String.prototype.endsWith = function (s) {
  return this.length >= s.length && this.substr(this.length - s.length) == s;
}

如果没有匹配,使用lastIndexOf只会创建不必要的CPU循环。

在所有这些长时间的答案之后,我发现这段代码简单易懂!

function end(str, target) {
  return str.substr(-target.length) == target;
}

String.prototype.endsWith()

总结

endsWith()方法确定字符串是否以另一个字符串的字符结束,并根据需要返回true或false。

语法

str.endsWith(searchString [, position]);

参数

searchString: 在此字符串的末尾要搜索的字符。 位置: 在这个字符串中搜索,就好像这个字符串只有这么长;默认为此字符串的实际长度,在此字符串长度建立的范围内。

描述

此方法允许您确定字符串是否以另一个字符串结束。

例子

var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

规范

ECMAScript语言规范第六版(ECMA-262)

浏览器兼容性

如果你不想使用lasIndexOf或substr,那么为什么不只是看看字符串在它的自然状态(即。一个数组)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

或者作为一个独立的函数

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}