user2981107
user2981107

Reputation: 87

replacing a variable substring in a string in javascript using regex

I want to replace all oldString's in string that are surrounded by whitespace, '.' , '(' or ')' using regex.

var string = ' (y) .y   y  rye';
var oldsString = 'y';
var regex = new RegExp('([.()\s])('+oldString+')([.()\s])','g');
var newString = 'x';
string = string.replace(regex, '$1'+newString+'$3');

setting regex to

var regex = new RegExp('([\.\(\)\s])('+oldString+')([\.\(\)\s])','g'); 

according to this website both methods should work: http://regex101.com/r/mM4xJ2 but when i try the code in node it only sets string to

' (x) .y   y  rye'

not

' (x) .x   x  rye'

Upvotes: 0

Views: 110

Answers (1)

tenub
tenub

Reputation: 3446

You need to double escape since you're compiling concatenated strings with a variable to a RegExp object:

var string = ' (y) .y   y  rye';
var oldString = 'y';
var regex = new RegExp('([.()\\s])('+oldString+')([.()\\s])','g');
var newString = 'x';
string = string.replace(regex, '$1'+newString+'$3');

This returns correctly:

' (x) .x   x  rye'

Upvotes: 1

Related Questions