How can I correctly check if a string does NOT contain a specific word?

前端 未结 6 1191
一个人的身影
一个人的身影 2021-01-11 15:01

I am currently trying to figure out how to solve the above named problem. Specifically I want to check if the string does not contain the word \"stream\" both in ca

6条回答
  •  生来不讨喜
    2021-01-11 15:20

    indexOf() is the correct approach and the case issue can be easily resolved by forcing the test string to lower or upper case before the test using .toLowerCase() or .toUpperCase():

    const lookupValue = "stream";
    const testString1 = "I might contain the word StReAm and it might be capitalized any way.";
    const testString2 = "I might contain the word steam and it might be capitalized any way.";
    
    function testString(testData, lookup){
      return testData.toLowerCase().indexOf(lookup) === -1;
    }
    
    function prettyPrint(yesNo){
       return "The string does" + (yesNo ? " NOT" : "") + " contain \"stream\" in some form."
    }
    
    console.log(prettyPrint(testString(testString1, lookupValue)));
    console.log(prettyPrint(testString(testString2, lookupValue)));

提交回复
热议问题