UPDATE (Nov 24th, 2015):
(更新(2015年11月24日):)
This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:
(该答案最初发布于2010年(六年前),因此请注意以下有见地的评论:)
ORIGINAL ANSWER:
(原始答案:)
I know this is a year old question... but I need this too and I need it to work cross-browser so... combining everyone's answer and comments and simplifying it a bit:
(我知道这是一个老问题了...但是我也需要这个,并且我需要它来跨浏览器工作,所以... 结合每个人的答案和评论并简化一点:)
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:
(另外,如果您不喜欢在本机数据结构的原型中填充东西,这是一个独立版本:)
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
EDIT: As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a typeof
check like so:
(编辑:正如@hamish在评论中指出的那样,如果您想在安全方面犯错,并检查是否已经提供了实现,则可以只添加typeof
检查,如下所示:)
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…