Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace array of words

x.replace(/old/gi. 'new');
x.replace(/whatever/gi. 'whatevernew');
x.replace(/car/gi. 'boat');

Is there a way to combine those in one regexp statement perhaps and array of old and new words. PHP solution is also welcome.

like image 563
Pinkie Avatar asked Feb 24 '23 17:02

Pinkie


1 Answers

You could do something like this:

var x = 'The old car is just whatever';
var arr = [{ old: /old/gi, new: 'new' },
           { old: /whatever/gi, new: 'whatevernew' },
           { old: /car/gi, new: 'boat' }];

for (var ii = 0; ii < arr.length; ii++) {
    x = x.replace(arr[ii].old, arr[ii].new);
}
like image 143
FishBasketGordo Avatar answered Feb 26 '23 08:02

FishBasketGordo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!