Search whole word in string

前端 未结 4 484
名媛妹妹
名媛妹妹 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:22

    Something like this will work:

    if(/\show\s/i.test(searchOnstring)){
        alert("Found how");
    }
    

    More on the test() method

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-18 10:33

    Here is a function that returns true with searchText is contained within searchOnString, ignoring case:

    function isMatch(searchOnString, searchText) {
      searchText = searchText.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      return searchOnString.match(new RegExp("\\b"+searchText+"\\b", "i")) != null;
    }
    

    Update, as mentioned you should escape the input, I'm using the escape function from https://stackoverflow.com/a/3561711/241294.

    0 讨论(0)
  • 2020-12-18 10:40

    Try this:

    var s = 'string to check', ss= 'to';
    if(s.indexOf(ss) != -1){
      //output : true
    }
    
    0 讨论(0)
提交回复
热议问题