endsWith在JavaScript中

Bob*_*mar 1085 javascript string ends-with

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

示例:我有一个字符串

var str = "mystring#";
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

cha*_*rit 1754

更新(2015年11月24日):

这个答案最初发布于2010年(六年前).所以请注意这些富有洞察力的评论:


原始答案:

我知道这是一年前的问题...但我也需要这个,我需要它跨浏览器工作所以... 结合每个人的答案和评论并简化它:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
Run Code Online (Sandbox Code Playgroud)
  • 不创建子字符串
  • 使用本机indexOf功能以获得最快的结果
  • 使用第二个参数跳过不必要的比较indexOf以跳过
  • 适用于Internet Explorer
  • 没有正则表达式的并发症

此外,如果您不喜欢在本机数据结构的原型中填充东西,这里是一个独立版本:

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
Run Code Online (Sandbox Code Playgroud)

编辑:正如@hamish在评论中所指出的,如果你想在安全方面犯错并检查是否已经提供了实现,你可以添加一个typeof支票,如下所示:

if (typeof String.prototype.endsWith !== 'function') {
    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}
Run Code Online (Sandbox Code Playgroud)

  • Google员工更新 - 看起来ECMA6添加了此功能.MDN文章还显示了一种填充物.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith (41认同)
  • 在现代浏览器上创建子串并不昂贵; 它可能是在2010年这个答案发布时.这些天,简单的`this.substr(-suffix.length)===后缀`方法在Chrome上最快,在IE11上与`indexOf`相同,在Firefox上只有4%慢(fergetaboutit领域):http:/ /jsperf.com/endswith-stackoverflow/14当结果为假时,全面加快:http://jsperf.com/endswith-stackoverflow-when-false当然,随着ES6添加`endsWith`,这一点没有实际意义.:-) (5认同)
  • 在未定义参数"suffix"时添加对情况的检查":if(typeof String.prototype.endsWith!=='function'){String.prototype.endsWith = function(suffix){return this.indexOf(suffix) ,this.length - ((suffix && suffix.length)|| 0))!== -1;};} (3认同)
  • @lukas.pukenis它跳到最后,只检查最后一个后缀的一个实例.如果搜索字符串出现在其他位置并不重要. (2认同)
  • 您提到的正则表达式并发症有哪些? (2认同)

Mik*_*uel 292

/#$/.test(str)
Run Code Online (Sandbox Code Playgroud)

将适用于所有浏览器,不需要猴子修补String,并且不需要扫描整个字符串,就像lastIndexOf没有匹配时一样.

如果要匹配可能包含正则表达式特殊字符的常量字符串,例如'$',则可以使用以下内容:

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

然后你可以像这样使用它

makeSuffixRegExp("a[complicated]*suffix*").test(str)
Run Code Online (Sandbox Code Playgroud)

  • 如果要检查常量子字符串,这很简单. (10认同)
  • @TomBrito,`lastIndexOf`仅在找不到匹配项时扫描整个字符串,或者在开头找到匹配项.如果最后匹配,那么它确实与后缀的长度成比例.是的,当`str`以`"asdf"结尾时,`/ asdf $/.test(str)`得到真. (3认同)
  • @Tom Brito,这是一个正则表达文字.语法来自Perl.请参阅https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions或了解不必要的详细信息,请参阅EcmaScript语言规范的第7.8.5节. (3认同)
  • +1用于跨浏览器兼容性.在Chrome 28.0.1500.72 m,Firefox 22.0和IE9上测试过. (2认同)

Phi*_*ham 89

  1. 不幸的是.
  2. if( "mystring#".substr(-1) === "#" ) {}

  • 但这在Internet Explorer中不起作用. (45认同)
  • @Anthony,嗯...所以使用.Length-1,有什么问题?if(mystring.substr(mystring.length-1)==="#"){}在IE中工作得很好. (14认同)
  • @ BrainSlugs83 - 这正是问题:'.length-1'语法在IE中起作用,' - 1'语法不起作用.这是值得记住的事情,所以给安东尼+1提示. (12认同)
  • mystring [mystring.length-1] ==='#'.适用于任何浏览器 (6认同)
  • 你不能用`slice()`吗?它在我的快速IE7测试中适用于我. (2认同)
  • @ahnbizcad 你的祈祷现在已经得到回应。IE浏览器 (2认同)

小智 66

来吧,这是正确的endsWith实现:

String.prototype.endsWith = function (s) {
  return this.length >= s.length && this.substr(this.length - s.length) == s;
}
Run Code Online (Sandbox Code Playgroud)

lastIndexOf如果没有匹配,使用只会创建不必要的CPU循环.

  • 可能应该使用`===`. (4认同)
  • @ BrainSlugs83已经有几年了,但现在这个方法并不比chakrit上面提到的'indexOf'方法快,而且在Safari下,它慢了30%!这是一个关于50个字符的字符串的失败案例的jsPerf测试:http://jsperf.com/endswithcomparison (3认同)
  • 同意.我真的觉得这是最高性能的解决方案,因为它具有早期中止/健全性检查,它简洁明了,优雅(重载字符串原型)和子串似乎比打开正则表达式引擎更少的资源. (2认同)

Jon*_*eet 56

这个版本避免了创建子字符串,并且不使用正则表达式(这里的一些正则表达式答案将起作用;其他正则表达式被破坏):

String.prototype.endsWith = function(str)
{
    var lastIndex = this.lastIndexOf(str);
    return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}
Run Code Online (Sandbox Code Playgroud)

如果性能对您很重要,那么测试是否lastIndexOf实际上比创建子字符串更快是值得的.(它很可能取决于你正在使用的JS引擎......)在匹配的情况下它可能会更快,当字符串很小时 - 但是当字符串很大时它需要回顾整个事情甚至虽然我们并不在乎:(

要检查单个字符,找到长度然后使用charAt可能是最好的方法.

  • 如果this.lastIndexOf()返回-1,则可以触发它返回true依赖于this.length和str.length的情况.添加lastIndexOf()!= -1的测试. (2认同)
  • @izb:比我的试图使用`str +"$"`作为正则表达式的答案被破坏了,因为它们可能不是有效的正则表达式. (2认同)

Nik*_*rov 25

没有看到slice方法的apporach .所以我只想把它放在这里:

function endsWith(str, suffix) {
    return str.slice(-suffix.length) === suffix
}
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案。不知道为什么它没有更多的赞成票。 (2认同)

小智 17

return this.lastIndexOf(str) + str.length == this.length;
Run Code Online (Sandbox Code Playgroud)

在原始字符串长度比搜索字符串长度小1并且找不到搜索字符串的情况下不起作用:

lastIndexOf返回-1,然后添加搜索字符串长度,并保留原始字符串的长度.

可能的解决方法是

return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
Run Code Online (Sandbox Code Playgroud)

  • 您已获得"在Jon Skeet答案中发现错误"徽章.查看您的个人资料了解详情 (30认同)

Ani*_*rni 16

来自developer.mozilla.org String.prototype.endsWith()

摘要

endsWith()方法确定字符串是否以另一个字符串的字符结尾,并根据需要返回true或false.

句法

str.endsWith(searchString [, position]);
Run Code Online (Sandbox Code Playgroud)

参数

  • searchString:要在此字符串末尾搜索的字符.

  • position:在这个字符串中搜索,好像这个字符串只有这么长; 默认为此字符串的实际长度,限制在此字符串长度建立的范围内.

描述

此方法允许您确定字符串是否以另一个字符串结尾.

例子

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
Run Code Online (Sandbox Code Playgroud)

产品规格

ECMAScript语言规范第6版(ECMA-262)

浏览器兼容性

浏览器兼容性


duc*_*lip 10

if( ("mystring#").substr(-1,1) == '#' )
Run Code Online (Sandbox Code Playgroud)

- 要么 -

if( ("mystring#").match(/#$/) )
Run Code Online (Sandbox Code Playgroud)


Moh*_*eeq 8

String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助

var myStr = “  Earth is a beautiful planet  ”;
var myStr2 = myStr.trim();  
//==“Earth is a beautiful planet”;

if (myStr2.startsWith(“Earth”)) // returns TRUE

if (myStr2.endsWith(“planet”)) // returns TRUE

if (myStr.startsWith(“Earth”)) 
// returns FALSE due to the leading spaces…

if (myStr.endsWith(“planet”)) 
// returns FALSE due to trailing spaces…
Run Code Online (Sandbox Code Playgroud)

传统的方式

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

function strEndsWith(str, suffix) {
    return str.match(suffix+"$")==suffix;
}
Run Code Online (Sandbox Code Playgroud)


小智 7

我不了解你,但是:

var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
Run Code Online (Sandbox Code Playgroud)

为什么正则表达式 为什么搞乱原型?SUBSTR?来吧...


Dhe*_*.S. 7

如果你正在使用lodash:

_.endsWith('abc', 'c'); // true
Run Code Online (Sandbox Code Playgroud)

如果不使用lodash,您可以从其来源借用.


Vin*_*ius 7

使用正则表达式的另一个快速替代方案对我来说就像一个魅力:

// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
Run Code Online (Sandbox Code Playgroud)


Ash*_*vis 6

I just learned about this string library:

http://stringjs.com/

Include the js file and then use the S variable like this:

S('hi there').endsWith('hi there')
Run Code Online (Sandbox Code Playgroud)

It can also be used in NodeJS by installing it:

npm install string
Run Code Online (Sandbox Code Playgroud)

Then requiring it as the S variable:

var S = require('string');
Run Code Online (Sandbox Code Playgroud)

The web page also has links to alternate string libraries, if this one doesn't take your fancy.