0

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'
0

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

3 Comments

It fails if 2 y is separated by 1 [.()\\s], eg. ` y.y `
If the string is ` y.y ` you cannot have a character match twice with RegEx since the first match ` y.` consumes the . prefix from the latter substring portion .y , so the correct result should be " x.y " as opposed to " x.x " despite all common sense.
... and since js regex does not support lookbehind you can't do it with it this simply. I'm just pointing out so the questioner would know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.