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

示例:我有一个字符串

var str = "mystring#";

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

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

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


当前回答

return this.lastIndexOf(str) + str.length == this.length;

在原始字符串长度小于搜索字符串长度并且没有找到搜索字符串的情况下不工作:

lastIndexOf返回-1,然后添加搜索字符串的长度,剩下的是原始字符串的长度。

一个可能的解决方案是

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length

其他回答

/#$/.test(str)

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

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

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

然后你可以这样使用它

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

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

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

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

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

return this.lastIndexOf(str) + str.length == this.length;

在原始字符串长度小于搜索字符串长度并且没有找到搜索字符串的情况下不工作:

lastIndexOf返回-1,然后添加搜索字符串的长度,剩下的是原始字符串的长度。

一个可能的解决方案是

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length

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)

浏览器兼容性

对于coffeescript

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