phantom phantom - 5 months ago 10x
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

(see below) I want to replace any word that is not
with the word

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

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


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


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;