Search whole word in string

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

提交回复
热议问题