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