phantom phantom - 7 months ago 12
Javascript Question

regex to change certain words in a string

I am trying to get my head around regular expressions. I thought the following would work, but unfortunately it isn't.

What I want to do:

Given a string

str
(see below) I want to replace any word that is not
shade
or
gravel
with the word
gravel
.

str = "gravel shade water grass people water shade";
output = str.replace(/([^gravel|^shade])/g,' gravel ');


output
should equal
gravel shade gravel gravel gravel gravel shade
. What I have is close enough but a bit off.

Answer

Your ([^gravel|^shade]) matches and captures into Group 1 any one single character that is not g, r, a, v, e, l, |, ^, and replace all of them with gravel.

You can use

/\b(?!(?:shade|gravel)\b)\w+\b/g

See the regex demo

Pattern description:

  • \b - leading word boundary
  • (?!(?:shade|gravel)\b) - a negative lookahead that will exclude matching whole words shade and gravel
  • \w+ - 1+ word characters (belonging to the [A-Za-z0-9_] set)
  • \b - trailing word boundary.

var str = 'gravel shade water grass people water shade';
var result = str.replace(/\b(?!(?:shade|gravel)\b)\w+\b/g, 'gravel');
document.body.innerHTML = result;