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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

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

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

其他回答

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)

浏览器兼容性

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

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

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

@chakrit的公认答案是一个坚实的方法来做自己。但是,如果您正在寻找一个打包的解决方案,我建议您考虑一下underscore。字符串,正如@mlunoe指出的那样。使用下划线。字符串,代码将是:

function endsWithHash(str) {
  return _.str.endsWith(str, '#');
}

对于coffeescript

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

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

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

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