Javascript Regex Word Boundary with optional non-word character

后端 未结 2 1445
灰色年华
灰色年华 2020-12-21 18:37

I am looking to find a keyword match in a string. I am trying to use word boundary, but this may not be the best case for that solution. The keyword could be any word, and c

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 18:57

    Check whether the keyword already begins with a special character. If it does, don't include it in the regular expression.

    var re;
    if ("#@".indexOf(keyword[0]) == -1) {
        re = new RegExp(`[@#]?\b${keyword}\b`);
    } else {
        re = new RegExp(`\b${keyword}\b`);
    }
    

提交回复
热议问题