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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

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

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

其他回答

String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

我希望这对你们有帮助

var myStr = “  Earth is a beautiful planet  ”;
var myStr2 = myStr.trim();  
//==“Earth is a beautiful planet”;

if (myStr2.startsWith(“Earth”)) // returns TRUE

if (myStr2.endsWith(“planet”)) // returns TRUE

if (myStr.startsWith(“Earth”)) 
// returns FALSE due to the leading spaces…

if (myStr.endsWith(“planet”)) 
// returns FALSE due to trailing spaces…

传统的方式

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

function strEndsWith(str, suffix) {
    return str.match(suffix+"$")==suffix;
}

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

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

这是endsWith的实现:

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

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

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

参考网址:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/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;
}