user6002037
user6002037

Reputation:

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.

Upvotes: 1

Views: 287

Answers (2)

anubhava
anubhava

Reputation: 786091

Here is a non-regex solution for your problem using split/join and array.map:

var str = "gravel shade water grass people water shade";
var repl = str.split(' ').map(function (w) {
           return (w!='gravel' && w!= 'shade')?'gravel':w; }).join(' ')

document.writeln("<pre>" + repl + "</pre>")
//=> "gravel shade gravel gravel gravel gravel shade"

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

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;

Upvotes: 2

Related Questions