In this article we will try find exact string using Javascript regular expression. 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 work 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
Final Solution to find exact string
"bar foo baz".match(/(^|\W)cos($|\W)/) // Finds a match
"foo baz bar".match(/(^|\W)cos($|\W)/) // Finds a match
Lastly hope you like the short explanation on how we can use some special characters to find an exact string using regex in javascript. Also you may see my blog Regex to match anything but two words which is opposite of this. See you in my next post. Till then enjoy coding 🙂