Javascript RegEx optimization

Below in the code section I have a piece that will take a word out of a string list and replace it with a space.  Moreover, I want to make sure that it only locates FULL words.  i.e. I dont want a search/replace for "ear" turning "clear" into "cl"  However, what I do not like about my solution is that I have to test for 4 cases:

Testing the word "cat":
word is surrounded in spaces "\s" (i.e. cat is in "A cat and a dog")
word is the entire string (i.e. cat is in "cat")
word is start of a string "^" (i.e. cat is in "cat in the hat")
word is at end of a string "$" (i.e. cat is in "My cat")

Below is the regex, can anyone optimize it to remove all the ORs ( | ) into a single check that will not require me to always be searching for the end and beginning of strings in this current manner?

var string = 'apple bear clear dear ear fear gold';
var replacement = trim(string.replace(/(\sear\s|^ear\s|\sear$|^ear$)/,' '));

// replacement should only remove the word "ear", not words that may also contain the letters "ear"
/ P.S. I already have my own trim function, so dont worry about that part of the JS

Open in new window

LVL 10
Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
What about:


where "\b" matches a word boundary. If "\b" doesn't work, then try the alternate boundary syntax of "\<" and "\>" for left and right boudaries, respectively.
js_vaughanAuthor Commented:
One more test case that seems to fail my version of the code that would be nice to have working in the final piece of code:
var myString = 'ear ear';
var replacement = trim(myString.replace(/(\sear\s|^ear\s|\sear$|^ear$)/g,' '));

// replacement will be "ear"

Open in new window

js_vaughanAuthor Commented:
The boundry got me most of the way there, except for I was left with extra spaces.  Below is my final code piece:
var replacement = trim(myString.replace(/(\s|\b)ear(\s|\b)/g,' '));

Open in new window

käµfm³d 👽Commented:
Glad it worked for you.

As a note, searching for word boundaries is non-matching--meaning the space or punctuation which the boundary matches is not actually part of the overall match. This is the reason why you still had spaces after the replace.
All Courses

From novice to tech pro — start learning today.