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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

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;
}

其他回答

这建立在@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可能是最好的方法。

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

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

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

这个问题已经问了很多年了。让我为想要使用投票最多的查克里特的答案的用户添加一个重要的更新。

'endsWith'函数已经作为ECMAScript 6的一部分添加到JavaScript(实验技术)

参考网址:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

因此,强烈建议添加检查答案中提到的本机实现是否存在。

他们都是非常有用的例子。添加string .prototype. endswith = function(str)将帮助我们简单地调用该方法来检查字符串是否以它结尾,regexp也会这样做。

我找到了比我更好的解决办法。谢谢大家。