javascript - 在 JavaScript 中结束

标签 javascript string ends-with

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

例子:我有一个字符串

var str = "mystring#";

我想知道该字符串是否以 # 结尾。如何查看?

  1. JavaScript 中有 endsWith() 方法吗?

  2. 我有一个解决方案是获取字符串的长度并获取最后一个字符并检查它。

这是最好的方法还是有其他方法?

最佳答案

更新(2015 年 11 月 24 日):

这个答案最初是在 2010 年(六年前)发布的。所以请注意这些有见地的评论:

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/

相关文章:

Java String.replace() - 替换的不仅仅是我指定的子字符串?

javascript - Mongoose isModified 和 isNew

javascript - D3js 折线图 Y 轴上的不同刻度大小

c# - 为什么字符串表现得像 ValueType

Java CompareTo 没有返回好的结果

java - String.endsWith() 不起作用

javascript - 如何在谷歌地图中拥有多个数据层?

c# - 单击链接时如何填充隐藏字段?

python - Python 字符串中的内联子字符串交换

如果路径以 "\"结尾,则 Powershell 命令修剪路径