Search code examples
javascriptregexword-boundary

Apply a word-boundary anchor to all tokens in a single regex


Say I have a list of tokens I want to match in a string: tok1, tok2, tok3, and so on...

I want a word-boundary to be applied to all of them in a single regex, but without copy-pasting \b everytime. Here is what I'm trying to avoid:

/\btok1\b|\btok2\b|\btok3\b|\btok4\b|\btok5\b/g

I tried:

/\b(str1|str2|str3|str4|str5)\b/g

But it doesn't work as expected with javascript .replace() method.

Is there another way to apply a word-boundary anchor to all tokens in a single regex ?

--- EDIT: ---

Example of regex I'm trying to factorize:

/\bjohn\b|\bjack\b|\bheather\b/g

Expected result :

john     //match
jack     //match
heather  //match
wheather //not match
hijack   //not match
johnny   //not match

Solution

  • You might use a non capturing group and add the tokens.

    Use the /g global flag to match all occurrences. Then use replace to replace the matches with your replacement value.

    \b(?:john|jack|heather)\b

    var str = "john, jack, heather, wheather, hijack, johnny";
    var res = str.replace(/\b(?:john|jack|heather)\b/g, "test");
    console.log(res);