How can I match a whole word in JavaScript?

前端 未结 4 681
栀梦
栀梦 2020-11-22 02:37

I am trying to search a single whole word through a textbox. Say I search "me", I should find all occurrences of the word "me" in the text, but not "

4条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 03:25

    You may use the following code:

    var stringTosearch ="test ,string, test"; //true
    var stringTosearch ="test string test"; //true
    var stringTosearch ="test stringtest"; //false
    var stringTosearch ="teststring test"; //false
    
    if (new RegExp("\\b"+"string"+"\\b").test(stringTosearch)) {
      console.log('string found');
      return true;
    } else {
      return false;
    }
    

提交回复
热议问题