Find exact string or match exact string with Javascript regex

Suppose we have text “foo bar baz” and want to find out the exact name bar using javascript regex. We can use below regex but as you can see in below example it find both bar as well as zbar which is not what we want.

"foo bar baz".match(/bar/)    // Finds a match
"foo zbar baz".match(/bar/)   // Finds a match. We don't want this

Here we can use the \W (capital W) special character to wrap your string. The \W special character matches any character that is not a word character so anything except A-Z, a-z, 0-9 and underscore. Now let’s see the results:

"foo bar baz".match(/\Wbar\W/)    // Finds a match
"foo zbar baz".match(/\Wbar\W/)   // Does not find a match

Good right. No, the above will not in case if bar is present at beginning or end of string. This does not work as by using \W we are trying to search for a non-word character and as before the first and after the last word we don not have any non-word character the regex fails to match.

"bar foo baz".match(/\Wcos\W/)    // Does not find a match
"foo baz bar".match(/\Wcos\W/)    // Does not find a match

So you will have to check for the beginning and end also with non word character. We can wrap our string between ^ (checks if string is at beginning) and $ (checks if string is at end) characters. We will use a group separated with or (|) operator.

  • (^|\W) – matches either the beginning of string or a non-word character
  • ($|\W) – matches either the end of string or a non-word character
"bar foo baz".match(/(^|\W)cos($|\W)/)    // Finds a match
"foo baz bar".match(/(^|\W)cos($|\W)/)    // Finds a match

Hope you like the short explanation on how we can use some special characters to find a exact string using regex in javascript. See you in my next post. Till then enjoy coding 🙂

Subscription