【问题标题】:endsWith in JavaScript在 JavaScript 中结束
【发布时间】:2010-09-21 19:00:41
【问题描述】:

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

例子:我有一个字符串

var str = "mystring#";

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

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

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

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

【问题讨论】:

标签: javascript string ends-with


【解决方案1】:
  1. 很遗憾没有。
  2. if( "mystring#".substr(-1) === "#" ) {}

【讨论】:

  • @Anthony,嗯...所以使用 .Length-1,有什么问题? if (mystring.substr(mystring.length-1) === "#") {} 在 IE 中运行良好。
  • @BrainSlugs83 - 这正是问题所在:'.length-1' 语法在 IE 中有效,而 '-1' 语法无效。需要牢记这一点,因此请 +1 给 Anthony 的小费。
  • 你不能用slice()吗?它适用于我的快速 IE7 测试。
  • 吓坏了 IE。它什么时候会死?
  • @ahnbizcad 您的祈祷现已得到回应。 RIP IE
【解决方案2】:
if( ("mystring#").substr(-1,1) == '#' )

-- 或者--

if( ("mystring#").match(/#$/) )

【讨论】:

    【解决方案3】:

    它们都是非常有用的例子。添加String.prototype.endsWith = function(str)将帮助我们简单地调用该方法来检查我们的字符串是否以它结尾,那么regexp也可以做到。

    我找到了比我更好的解决方案。谢谢大家。

    【讨论】:

      【解决方案4】:

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

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

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

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

      【讨论】:

      • 如果 this.lastIndexOf() 返回 -1,你可以遇到依赖 this.length 和 str.length 返回 true 的情况。添加一个 lastIndexOf() != -1 的测试。
      • 为什么regex方法坏了?
      • @izb:尝试使用str+"$" 作为正则表达式的比我的答案更老的答案被破坏了,因为它们可能不是有效的正则表达式。
      【解决方案5】:
      return this.lastIndexOf(str) + str.length == this.length;
      

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

      lastIndexOf 返回 -1,然后添加搜索字符串长度,剩下的是原始字符串的长度。

      一个可能的解决办法是

      return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
      

      【讨论】:

      • 您已获得“在 Jon Skeet 的回答中发现错误”徽章。有关详细信息,请参阅您的个人资料。
      【解决方案6】:
      /#$/.test(str)
      

      适用于所有浏览器,不需要猴子修补String,也不需要像lastIndexOf 在没有匹配项时扫描整个字符串。

      如果你想匹配一个可能包含正则表达式特殊字符的常量字符串,比如'$',那么你可以使用如下:

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

      然后你就可以这样使用了

      makeSuffixRegExp("a[complicated]*suffix*").test(str)
      

      【讨论】:

      • 如果您要检查一个常量子字符串,这很简单。
      • lastIndexOf 扫描所有字符串?我以为它会从头到尾搜索。
      • @TomBrito, lastIndexOf 仅在找不到匹配项或在开头找到匹配项时扫描整个字符串。如果最后有匹配,那么它的工作与后缀的长度成正比。是的,当str"asdf" 结尾时,/asdf$/.test(str) 产生 true。
      • @Tom Brito,这是一个正则表达式文字。语法是从 Perl 借来的。请参阅developer.mozilla.org/en/Core_JavaScript_1.5_Guide/… 或有关不必要的详细信息,请参阅 EcmaScript 语言规范的第 7.8.5 节。
      • +1 表示跨浏览器兼容性。在 Chrome 28.0.1500.72 m、Firefox 22.0 和 IE9 上测试。
      【解决方案7】:

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

      String.prototype.endsWith = function (s) {
        return this.length >= s.length && this.substr(this.length - s.length) == s;
      }
      

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

      【讨论】:

      • 同意。我真的觉得这是提供的最高效的解决方案,因为它具有早期的中止/健全性检查,它简短而简洁,它很优雅(重载字符串原型)并且子字符串似乎比启动正则表达式引擎对资源的影响要小得多。
      • 也喜欢这个解决方案。只是函数名拼错了。应该是“endsWith”。
      • @BrainSlugs83 已经好几年了,但现在这个方法并不比上面chakrit提到的'indexOf'方法快,而且在Safari下,它慢了30%!这是一个针对大约 50 个字符的字符串的失败案例的 jsPerf 测试:jsperf.com/endswithcomparison
      • 可能应该使用===
      【解决方案8】:

      更新(2015 年 11 月 24 日):

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

      Google 员工更新 - ECMA6 似乎添加了此功能。 MDN 文章还展示了一个 polyfill。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

      在现代浏览器上创建子字符串并不昂贵;发布此答案时很可能是在 2010 年。如今,简单的this.substr(-suffix.length) === suffix 方法在 Chrome 上最快,在 IE11 上与 indexOf 相同,在 Firefox 上仅慢 4%(fergetaboutit 领域):jsperf.com/endswith-stackoverflow/14 当结果为假时,整体速度更快:jsperf.com/endswith-stackoverflow-when-false 当然,在 ES6 中添加了 endsWith,这一点没有实际意义。 :-)


      原始答案:

      我知道这是一个有年头的问题......但我也需要这个,而且我需要它来跨浏览器工作,所以...... 结合每个人的答案和 cmets 并稍微简化一下:

      String.prototype.endsWith = function(suffix) {
          return this.indexOf(suffix, this.length - suffix.length) !== -1;
      };
      
      • 不创建子字符串
      • 使用原生 indexOf 函数以获得最快的结果
      • 使用indexOf 的第二个参数跳过不必要的比较以向前跳过
      • 在 Internet Explorer 中工作
      • 没有正则表达式并发症

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

      function endsWith(str, suffix) {
          return str.indexOf(suffix, str.length - suffix.length) !== -1;
      }
      

      编辑:正如@hamish 在 cmets 中指出的那样,如果您想在安全方面犯错并检查是否已经提供了实现,您可以添加一个 typeof 检查,例如所以:

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

      【讨论】:

      • Google 员工更新 - 看起来 ECMA6 增加了这个功能。 MDN 文章还展示了一个 polyfill。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
      • @lukas.pukenis 它跳到最后,只在最后检查一个后缀实例。搜索字符串是否出现在其他地方并不重要。
      • 添加对未定义参数“后缀”的情况的检查”: if (typeof String.prototype.endsWith !== 'function') { String.prototype.endsWith = function(suffix ) { return this.indexOf(suffix, this.length - ((suffix && suffix.length) || 0)) !== -1; }; }
      • 你提到的正则表达式并发症是什么?
      • 在现代浏览器上创建子字符串并不昂贵;发布此答案时很可能是在 2010 年。如今,简单的this.substr(-suffix.length) === suffix 方法在 Chrome 上最快,在 IE11 上与indexOf 相同,在 Firefox 上仅慢 4%(fergetaboutit 领域):jsperf.com/endswith-stackoverflow/14 当结果为 false 时,整体速度更快:@ 987654328@ 当然,在 ES6 中添加endsWith,这一点没有实际意义。 :-)
      【解决方案9】:
      function check(str)
      {
          var lastIndex = str.lastIndexOf('/');
          return (lastIndex != -1) && (lastIndex  == (str.length - 1));
      }
      

      【讨论】:

        【解决方案10】:

        如果您不想使用 lasIndexOf 或 substr 那么为什么不直接查看自然状态下的字符串(即数组)

        String.prototype.endsWith = function(suffix) {
            if (this[this.length - 1] == suffix) return true;
            return false;
        }
        

        或作为独立功能

        function strEndsWith(str,suffix) {
            if (str[str.length - 1] == suffix) return true;
            return false;
        }
        

        【讨论】:

          【解决方案11】:

          未来证明和/或防止覆盖现有原型的方法是测试检查它是否已添加到字符串原型中。这是我对非正则表达式高度评价的版本的看法。

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

          【讨论】:

          • 使用if (!String.prototype.hasOwnProperty("endsWith")) 是最好的方法。使用typeof,“MooTools 和其他一些 AJAX 库会让你搞砸”,根据“Crockford on JavaScript - Level 7: ECMAScript 5: The New Parts”,15:50 分钟。
          【解决方案12】:
          String.prototype.endWith = function (a) {
              var isExp = a.constructor.name === "RegExp",
              val = this;
              if (isExp === false) {
                  a = escape(a);
                  val = escape(val);
              } else
                  a = a.toString().replace(/(^\/)|(\/$)/g, "");
              return eval("/" + a + "$/.test(val)");
          }
          
          // example
          var str = "Hello";
          alert(str.endWith("lo"));
          alert(str.endWith(/l(o|a)/));
          

          【讨论】:

            【解决方案13】:
            String.prototype.endsWith = function(str) 
            {return (this.match(str+"$")==str)}
            
            String.prototype.startsWith = function(str) 
            {return (this.match("^"+str)==str)}
            

            希望对你有帮助

            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…
            

            传统方式

            function strStartsWith(str, prefix) {
                return str.indexOf(prefix) === 0;
            }
            
            function strEndsWith(str, suffix) {
                return str.match(suffix+"$")==suffix;
            }
            

            【讨论】:

            • 你必须为正则表达式转义序列转义你的字符串
            • 正则表达式即使在快速语言中也很慢。只需检查字符串的结尾。
            【解决方案14】:

            我不了解你,但是:

            var s = "mystring#";
            s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
            

            为什么是正则表达式?为什么要搞乱原型?子字符串?来吧...

            【讨论】:

            • '因为有时 W.E.T. 会更好
            【解决方案15】:

            这建立在@charkit 接受的答案之上,允许字符串数组或字符串作为参数传入。

            if (typeof String.prototype.endsWith === 'undefined') {
                String.prototype.endsWith = function(suffix) {
                    if (typeof suffix === 'String') {
                        return this.indexOf(suffix, this.length - suffix.length) !== -1;
                    }else if(suffix instanceof Array){
                        return _.find(suffix, function(value){
                            console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
                            return this.indexOf(value, this.length - value.length) !== -1;
                        }, this);
                    }
                };
            }
            

            这需要 underscorejs - 但可能可以调整以删除下划线依赖项。

            【讨论】:

            • 这是一个糟糕的解决方案,如果您已经在使用下划线,您应该将此 epeli.github.io/underscore.string 添加到您的依赖项中并使用它们的实现:_.str.endsWith
            【解决方案16】:
            if(typeof String.prototype.endsWith !== "function") {
                /**
                 * String.prototype.endsWith
                 * Check if given string locate at the end of current string
                 * @param {string} substring substring to locate in the current string.
                 * @param {number=} position end the endsWith check at that position
                 * @return {boolean}
                 *
                 * @edition ECMA-262 6th Edition, 15.5.4.23
                 */
                String.prototype.endsWith = function(substring, position) {
                    substring = String(substring);
            
                    var subLen = substring.length | 0;
            
                    if( !subLen )return true;//Empty string
            
                    var strLen = this.length;
            
                    if( position === void 0 )position = strLen;
                    else position = position | 0;
            
                    if( position < 1 )return false;
            
                    var fromIndex = (strLen < position ? strLen : position) - subLen;
            
                    return (fromIndex >= 0 || subLen === -fromIndex)
                        && (
                            position === 0
                            // if position not at the and of the string, we can optimise search substring
                            //  by checking first symbol of substring exists in search position in current string
                            || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
                        )
                        && this.indexOf(substring, fromIndex) === fromIndex
                    ;
                };
            }
            

            好处:

            【讨论】:

              【解决方案17】:

              不要使用正则表达式。即使在快速的语言中,它们也很慢。只需编写一个检查字符串结尾的函数。这个库有很好的例子:groundjs/util.js。 向 String.prototype 添加函数时要小心。这段代码有很好的例子说明如何做到这一点:groundjs/prototype.js 一般来说,这是一个不错的语言级库:groundjs 也可以看看lodash

              【讨论】:

                【解决方案18】:

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

                总结

                endsWith() 方法判断一个字符串是否以另一个字符串的字符结尾,根据需要返回真或假。

                语法

                str.endsWith(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
                

                规格

                ECMAScript Language Specification 6th Edition (ECMA-262)

                浏览器兼容性

                【讨论】:

                  【解决方案19】:

                  我刚刚了解了这个字符串库:

                  http://stringjs.com/

                  包含 js 文件,然后像这样使用S 变量:

                  S('hi there').endsWith('hi there')
                  

                  通过安装也可以在NodeJS中使用:

                  npm install string
                  

                  然后要求它作为S 变量:

                  var S = require('string');
                  

                  如果您不喜欢这个,该网页还包含指向备用字符串库的链接。

                  【讨论】:

                    【解决方案20】:
                    function strEndsWith(str,suffix) {
                      var reguex= new RegExp(suffix+'$');
                    
                      if (str.match(reguex)!=null)
                          return true;
                    
                      return false;
                    }
                    

                    【讨论】:

                    • 最好解释一下为什么你的代码可以解决问题。请参阅指南How to Answer
                    • 应扫描后缀参数以查找必须转义的正则表达式。使用 indexOf 或 lastIndexOf 似乎是一个更好的选择。
                    • 如果后缀包含以下任何字符将不起作用:.*+?^=!:${}()[]/\
                    【解决方案21】:

                    咖啡脚本

                    String::endsWith = (suffix) ->
                      -1 != @indexOf suffix, @length - suffix.length
                    

                    【讨论】:

                      【解决方案22】:

                      这么一个小问题,这么多东西,就用这个正则表达式

                      var str = "mystring#";
                      var regex = /^.*#$/
                      
                      if (regex.test(str)){
                        //if it has a trailing '#'
                      }

                      【讨论】:

                        【解决方案23】:

                        @chakrit 接受的答案是您自己做的可靠方法。但是,如果您正在寻找打包的解决方案,我建议您查看underscore.string,正如@mlunoe 指出的那样。使用 underscore.string,代码将是:

                        function endsWithHash(str) {
                          return _.str.endsWith(str, '#');
                        }
                        

                        【讨论】:

                          【解决方案24】:

                          如果您使用的是lodash

                          _.endsWith('abc', 'c'); // true
                          

                          如果不使用lodash,可以借用它的source

                          【讨论】:

                            【解决方案25】:

                            这个问题已经很多年了。让我为想要使用投票最多的 chakrit 答案的用户添加一个重要更新。

                            'endsWith' 函数已作为 ECMAScript 6(实验性技术)的一部分添加到 JavaScript 中

                            参考这里:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

                            因此强烈建议添加检查是否存在本机实现,如答案中所述。

                            【讨论】:

                              【解决方案26】:

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

                              // Would be equivalent to:
                              // "Hello World!".endsWith("World!")
                              "Hello World!".match("World!$") != null
                              

                              【讨论】:

                                【解决方案27】:

                                没有看到使用slice 方法的方法。所以我就把它留在这里:

                                function endsWith(str, suffix) {
                                    return str.slice(-suffix.length) === suffix
                                }
                                

                                【讨论】:

                                • 你可以再简化一点:return str.slice(-1) === suffix;
                                • 这是最好的答案。不知道为什么它没有更多的赞成票。
                                【解决方案28】:

                                7 岁的帖子,但我无法理解前几篇帖子,因为它们很复杂。所以,我写了自己的解决方案:

                                function strEndsWith(str, endwith)
                                {
                                    var lastIndex = url.lastIndexOf(endsWith);
                                    var result = false;
                                    if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
                                    {
                                        result = true;
                                    }
                                    return result;
                                }
                                

                                【讨论】:

                                  【解决方案29】:

                                  经过这么长的回答,我发现这段代码简单易懂!

                                  function end(str, target) {
                                    return str.substr(-target.length) == target;
                                  }
                                  

                                  【讨论】:

                                    【解决方案30】:

                                    这是endsWith的实现:

                                    String.prototype.endsWith = function (str) {
                                      return (this.length >= str.length) && (this.substr(this.length - str.length) === str);
                                    }
                                    

                                    【讨论】:

                                      猜你喜欢
                                      • 1970-01-01
                                      • 2011-03-04
                                      • 2021-03-01
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2020-11-06
                                      • 1970-01-01
                                      • 2022-01-20
                                      相关资源
                                      最近更新 更多