Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

javascript - JavaScript中的endsWith(endsWith in JavaScript)

How can I check if a string ends with a particular character in JavaScript?

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

Example: I have a string

(示例:我有一个字符串)

var str = "mystring#";

I want to know if that string is ending with # .

(我想知道该字符串是否以#结尾。)

How can I check it?

(我该如何检查?)

  1. Is there a endsWith() method in JavaScript?

    (JavaScript中是否有endsWith()方法?)

  2. One solution I have is take the length of the string and get the last character and check it.

    (我有一个解决方案是获取字符串的长度并获取最后一个字符并进行检查。)

Is this the best way or there is any other way?

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

  ask by Bobby Kumar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
};
  • Doesn't create a substring

    (不创建子字符串)

  • Uses native indexOf function for fastest results

    (使用本机indexOf函数可获得最快的结果)

  • Skip unnecessary comparisons using the second parameter of indexOf to skip ahead

    (使用indexOf的第二个参数跳过不必要的比较以向前跳过)

  • Works in Internet Explorer

    (在Internet Explorer中工作)

  • NO Regex complications

    (没有正则表达式并发症)


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;
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...