【问题标题】:Check if text is in a string检查文本是否在字符串中
【发布时间】:2011-09-30 15:52:50
【问题描述】:

我想检查一些文本是否在字符串中,例如我有一个字符串

str = "car, bycicle, bus"

我还有另一个字符串

str2 = "car"

我想检查str2是否在str中。

我是 javascript 的新手,所以请多多包涵:)

问候

【问题讨论】:

标签: javascript


【解决方案1】:
if(str.indexOf(str2) >= 0) {
   ...
}

或者如果你想走正则表达式路线:

if(new RegExp(str2).test(str)) {
  ...
}

但是在后者中您可能会遇到转义(元字符)的问题,因此第一种方法更容易。

【讨论】:

  • 这应该可以完美运行。 indexOf 返回str2str 中的开头索引。如果它不在数组中,则返回 -1。
  • 我喜欢使用 != -1 变体。 ---- if(str.indexOf(str2) != -1) {}
【解决方案2】:

ES5

if(str.indexOf(str2) >= 0) {
   ...
}

ES6

if (str.includes(str2)) {

}

【讨论】:

    【解决方案3】:

    str.lastIndexOf(str2) >= 0; 这应该可以。但未经测试。

    let str = "car, bycicle, bus";
    let str2 = "car";
    console.log(str.lastIndexOf(str2) >= 0);

    【讨论】:

    • 为什么使用lastIndexOf 而不仅仅是indexOf
    • 只是习惯的力量,我在过去使用 indexOf...lastIndexOf 的工作方式是一样的,据我所知,当只有一个正在查找的字符串实例时。跨度>
    • 有趣。什么情况下indexOf会闹事?
    • 如果您正在寻找不止一种方法来给这只猫剥皮,您可以将var items = str.split(",") 放入一个数组中,然后遍历数组项检查 items[i] == str2....跨度>
    • @Hughes,完全不是说我的方法是正确的,也不是我在实践中做了很长时间的事情,但是,var x = ',,'x.indexOf(x) == 0x.lastIndexOf(x) == 1,你会得到两个不同的结果,并且根据逻辑,您可能会遇到一些问题。
    【解决方案4】:

    请使用这个:

    var s = "foo";
    alert(s.indexOf("oo") > -1);
    

    【讨论】:

    • 除了您使用>而不是>=之外,这与接受的答案有何不同?
    • Ram,两者都一样!!如果您会看到条件,那么两者都表明您使用“indexOf”函数获得的值应该大于或等于 0。
    • 两者都是一样的,这就是我的意思。如果需要,请不要在问题中添加重复的答案,而是对现有答案进行投票。
    【解决方案5】:

    使用内置的.includes()字符串方法检查子字符串是否存在。
    它返回布尔值,指示是否包含子字符串。

    const string = "hello world";
    const subString = "world";
    
    console.log(string.includes(subString));
    
    if(string.includes(subString)){
       // SOME CODE
    }
    

    【讨论】:

      【解决方案6】:

      如果您只想检查字符串中的子字符串,您可以使用indexOf,但如果您想检查单词是否在字符串中,其他答案可能无法正常工作,例如:

      str = "carpet, bycicle, bus"
      str2 = "car"
      What you want car word is found not car in carpet
      if(str.indexOf(str2) >= 0) {
        // Still true here
      }
      // OR 
      if(new RegExp(str2).test(str)) {
        // Still true here 
      }
      

      因此,您可以稍微改进一下正则表达式以使其正常工作

      str = "carpet, bycicle, bus"
      str1 = "car, bycicle, bus"
      stringCheck = "car"
      // This will false
      if(new RegExp(`\b${stringCheck}\b`).test(str)) {
        
      }
      // This will true
      if(new RegExp(`\b${stringCheck}\b`,"g").test(str1)) {
        
      }
      

      【讨论】:

        猜你喜欢
        • 2014-12-11
        • 1970-01-01
        • 2016-01-02
        • 2012-02-19
        • 1970-01-01
        • 2019-02-27
        • 2013-03-01
        • 2020-04-15
        • 1970-01-01
        相关资源
        最近更新 更多