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 = "gravel shade water grass people water shade";
output = str.replace(/([^gravel|^shade])/g,' gravel ');
gravel shade gravel gravel gravel gravel shade
([^gravel|^shade]) matches and captures into Group 1 any one single character that is not
^, and replace all of them with
You can use
See the regex demo
\b- leading word boundary
(?!(?:shade|gravel)\b)- a negative lookahead that will exclude matching whole words
\w+- 1+ word characters (belonging to the
\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;