如何在 JavaScript 中检查字符串是否以特定字符结尾?
例子:我有一个字符串
var str = "mystring#";
我想知道该字符串是否以 #
结尾。如何查看?
JavaScript 中有
endsWith()
方法吗?我有一个解决方案是获取字符串的长度并获取最后一个字符并检查它。
这是最好的方法还是有其他方法?
最佳答案
更新(2015 年 11 月 24 日):
这个答案最初是在 2010 年(六年前)发布的。所以请注意这些有见地的评论:
- Shauna -
Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple
this.substr(-suffix.length) === suffix
approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: https://jsben.ch/OJzlM And faster across the board when the result is false: jsperf.com/endswith-stackoverflow-when-false Of course, with ES6 adding endsWith, the point is moot. :-)
原始答案:
我知道这是一个老问题......但我也需要这个,我需要它来跨浏览器工作,所以......结合每个人的答案和评论并稍微简化一下:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
- 不创建子字符串
- 使用原生
indexOf
函数以获得最快的结果 - 使用
indexOf
的第二个参数跳过不必要的比较以向前跳过 - 在 Internet Explorer 中工作
- 没有正则表达式并发症
另外,如果您不喜欢在原生数据结构的原型(prototype)中填充东西,这里有一个独立版本:
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
编辑:正如@hamish 在评论中指出的那样,如果您想在安全方面犯错并检查是否已经提供了实现,您可以添加一个 typeof
像这样检查:
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
关于javascript - 在 JavaScript 中结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/280634/