Javascript and Regex - Strict match of words in the string

792 Views Asked by At

I have a string like this:

Free-coffee and coffee-free is free coffee

I need to match and replace only alone word free but not words {Free}-coffee and coffee-{free}

Idea is to mark bad words inside string and add HTML tag <strong> like this:

Free-coffee and coffee-free is <strong>free<strong> coffee.

I try with space but sometimes fail if before this sentence have space.

Here is my current regex:

/(\sfree\s|\sfree|free\s)/ig

NOTE: This need to be case insensitive.

And here is example of code:

var text = "Free-coffee and coffee-free is free coffee";
text = text.replace(/(\sfree\s|\sfree|free\s)/ig, " <strong>strong</strong> ");

Help me please.

1

There are 1 best solutions below

3
On BEST ANSWER

Use the following regex pattern:

var text = "Free-coffee and coffee-free is free coffee";
text = text.replace(/(^|\s)(free)(\s|$)/ig, "$1<strong>$2</strong>$3");

console.log(text);

(^|\s) - ensures that free word is either at the start of the string OR preceded by space

(\s|$) - ensures that free word is either at the end of the string OR followed by space