Search whole word in string

前端 未结 4 562
名媛妹妹
名媛妹妹 2020-12-18 09:48

I am looking for a function written in javascript ( not in jquery) which will return true if the given word exactly matches ( should not be case sensitive).

like..

4条回答
  •  眼角桃花
    2020-12-18 10:32

    You could use regular expressions:

    \bhow\b
    

    Example:

    /\bhow\b/i.test(searchOnstring);
    

    If you want to have a variable word (e.g. from a user input), you have to pay attention to not include special RegExp characters.

    You have to escape them, for example with the function provided in the MDN (scroll down a bit):

    function escapeRegExp(string){
      return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
    
    var regex = '\\b';
    regex += escapeRegExp(yourDynamicString);
    regex += '\\b';
    
    new RegExp(regex, "i").test(searchOnstring);
    

提交回复
热议问题