【问题标题】:How to know that a string starts/ends with a specific string in jQuery?如何知道一个字符串以 jQuery 中的特定字符串开始/结束?
【发布时间】:2011-04-12 12:48:04
【问题描述】:

我想知道一个字符串是在jQuery中以指定的字符/字符串开头还是以它结尾。

例如:

var str = 'Hello World';

if( str starts with 'Hello' ) {
   alert('true');
} else {
   alert('false');
}

if( str ends with 'World' ) {
   alert('true');
} else {
   alert('false');
}

如果没有任何功能,还有其他选择吗?

【问题讨论】:

  • 是的,如果你的用户使用比 Edge 更早的 IE,请不要使用 ES6。

标签: javascript jquery string


【解决方案1】:

对于startswith,你可以使用indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

您可以根据字符串长度进行数学运算以确定“endswith”。

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

【讨论】:

  • 你可能想用lastIndexOf()作为结尾;)
  • 小心,IE8 浏览器不支持 IndexOf。与 lastIndexOf 相同。
  • 我为造成的混乱道歉。我指的是仅支持 iE9+ 的 Array.prototype.indexOf() 而不是 IE4+ 支持的 String.prototype.indexOf()
  • 对于这样一个简单的用例,比使用正则表达式更安全的答案。应该可能被接受的答案。
  • 'endswith' 的代码有问题。检查字符串中未出现且长度为 = (word - 1) 的字符串时。例如。 ("1234".lastIndexOf('Hello') == "1234".length - 'Hello'.length) 结果为真。
【解决方案2】:

一种选择是使用正则表达式:

if (str.match("^Hello")) {
   // do this if begins with Hello
}

if (str.match("World$")) {
   // do this if ends in world
}

【讨论】:

  • 在 jQuery 中我尝试了 str.startsWith('some checks string ..') 这给了我一个错误提示,startsWith method not found.. :( 但 str.match 有效。感谢您的回答
  • 请注意您正在检查的字符串不包含任何正则表达式保留字符。
  • 这将返回匹配的字符串,但不返回布尔值。
  • var isUnavailable = $("#StatusId option:selected").text().match("^Unavailable - "); - 为什么当所选选项“不可用 - 其他”时返回null返回null? span>
【解决方案3】:

不需要 jQuery 来做到这一点。你可以编写一个 jQuery 包装器,但它没有用,所以你应该更好地使用

var str = "Hello World";

window.alert("Starts with Hello ? " + /^Hello/i.test(str));        

window.alert("Ends with Hello ? " + /Hello$/i.test(str));

因为 match() 方法已被弃用。

PS : RegExp 中的“i”标志是可选的,代表不区分大小写(因此对于“hello”、“hEllo”等它也会返回 true)。

【讨论】:

  • 你能提供一个关于 match() 被弃用的文档的链接吗?快速的 Google 搜索不会返回任何内容。
  • 我几年前在网上看到的,现在恐怕已经找不到确切的位置了。
【解决方案4】:

你并不真的需要 jQuery 来完成这些任务。在 ES6 规范中,他们已经有了开箱即用的方法 startsWithendsWith

var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

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

Currently available in FF and Chrome。对于旧浏览器,您可以使用他们的 polyfills 或 substr

【讨论】:

    【解决方案5】:

    你总是可以像这样扩展String原型:

    //  Checks that string starts with the specific string
    if (typeof String.prototype.startsWith != 'function') {
        String.prototype.startsWith = function (str) {
            return this.slice(0, str.length) == str;
        };
    }
    
    //  Checks that string ends with the specific string...
    if (typeof String.prototype.endsWith != 'function') {
        String.prototype.endsWith = function (str) {
            return this.slice(-str.length) == str;
        };
    }
    

    并像这样使用它:

    var str = 'Hello World';
    
    if( str.startsWith('Hello') ) {
       // your string starts with 'Hello'
    }
    
    if( str.endsWith('World') ) {
       // your string ends with 'World'
    }
    

    【讨论】:

      【解决方案6】:

      ES6 现在支持startsWith()endsWith() 方法来检查strings 的开始和结束。如果您想支持 pre-es6 引擎,您可能需要考虑将建议的方法之一添加到 String 原型。

      if (typeof String.prototype.startsWith != 'function') {
        String.prototype.startsWith = function (str) {
          return this.match(new RegExp("^" + str));
        };
      }
      
      if (typeof String.prototype.endsWith != 'function') {
        String.prototype.endsWith = function (str) {
          return this.match(new RegExp(str + "$"));
        };
      }
      
      var str = "foobar is not barfoo";
      console.log(str.startsWith("foob"); // true
      console.log(str.endsWith("rfoo");   // true
      

      【讨论】:

      • 任何包含需要转义以便在正则表达式中使用的字符的字符串(例如 ()[].)都会破坏您的 polyfill 方法。您需要使用正则表达式转义函数准备字符串。甚至更好:使用来自core-js的经过实战考验的polyfill
      猜你喜欢
      • 2013-05-18
      • 1970-01-01
      • 2017-02-20
      • 2019-06-02
      • 2023-03-27
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      相关资源
      最近更新 更多