2

I need to pick specific words from string. Words are dynamic.

const KEY_VAL_MAP = { car: vehicle };
const KEY  = 'car';

let sampleString = 'hey this i need to replace car ${car}';

sampleString = sampleString.replace(new RegExp(`\\b(?:${KEY})\\b`, 'g'), KEY_VAL_MAP[_key]); 

the result expected is : 'hey this i need to replace vehicle ${car}';

With the above regex it will replace every car with vehicle. What needs to be updated in regex so that everything in string under ${} is excluded.

Gaurav Soni
  • 391
  • 1
  • 8
  • 26

2 Answers2

4

You may use this regex to avoid matching ${...} substring:

(?<!\$\{)\bcar\b(?!})

RegEx Demo

RegEx Details:

  • (?<!\$\{): Negative Lookbehind to assert that we don't have ${ before our matching word
  • \bcar\b: Match full word car
  • (?!}): Negative Lookahead to assert that we don't have } after our matching word

Code:

const KEY_VAL_MAP = { car: 'vehicle' };
const KEY  = 'car';

let sampleString = 'hey this i need to replace car ${car}';

sampleString = sampleString.replace(new RegExp(`(?<!\\$\\{)\\b(?:${KEY})\\b(?!})`, 'g'), KEY_VAL_MAP[KEY]);

console.log(sampleString);
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You can use a negative lookahead and behind to exclude the matches for words in between ${}.

(?<!\$\{)\bcar\b(?!\})

const KEY_VAL_MAP = { car: 'vehicle' };
const KEY  = 'car';

let sampleString = 'hey this i need to replace car ${car}';

sampleString = sampleString.replace(new RegExp(`(?<!\\$\\{)\\b${KEY}\\b(?!\\})`, 'g'), KEY_VAL_MAP[KEY]);

console.log(sampleString);

Also, some browsers(such as safari) doesn't support lookbehinds. So if you want you code also work on those browsers, you may use another workaround using a capture group:

(\$\{car\})|\bcar\b

If the group catches anything, don't touch. Otherwise replace.

const KEY_VAL_MAP = { car: 'vehicle' };
const KEY  = 'car';

let sampleString = 'hey this i need to replace car ${car}';

sampleString = sampleString.replace(new RegExp(`(\\$\\{${KEY}\\})|\\b${KEY}\\b`, 'g'), (_, g) => g ?? KEY_VAL_MAP[KEY]);

console.log(sampleString);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60