Check if text is in a string

后端 未结 6 1885
北荒
北荒 2020-12-29 04:50

I want to check is some text is in a string for instance i have a string

str = \"car, bycicle, bus\"

and I have another string



        
相关标签:
6条回答
  • 2020-12-29 04:59

    If you just want to check substring in a string you can use indexOf but if you want to check if the word is in the string or not, the other answers might not work correctly for example:

    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 
    }
    

    So you can improve the regex a bit to make it work

    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)) {
      
    }
    
    0 讨论(0)
  • 2020-12-29 04:59

    Use the builtin .includes() string method to check for the existence of sub-string.
    It return boolean which indicates if the sub-string included or not.

    const string = "hello world";
    const subString = "world";
    
    console.log(string.includes(subString));
    
    if(string.includes(subString)){
       // SOME CODE
    }
    
    0 讨论(0)
  • 2020-12-29 05:02

    ES5

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

    ES6

    if (str.includes(str2)) {
    
    }
    
    0 讨论(0)
  • 2020-12-29 05:19
    if(str.indexOf(str2) >= 0) {
       ...
    }
    

    Or if you want to go the regex route:

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

    However you may face issues with escaping (metacharacters) in the latter, so the first route is easier.

    0 讨论(0)
  • 2020-12-29 05:19

    Please use this :

    var s = "foo";
    alert(s.indexOf("oo") > -1);
    
    0 讨论(0)
  • 2020-12-29 05:20

    str.lastIndexOf(str2) >= 0; this should work. untested though.

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

    0 讨论(0)
提交回复
热议问题