fefe
fefe

Reputation: 9055

Using Javascripts Regexp to replace string part based on variable

I have the following snippet where I try to replace on variable values with javascripts Regexp. But I can not figure out how should look to work

var str = 'display = 12;14&test =124;562'; 
var str2 = 'display';
new_values = '123;185';
var new_str = str.replace(new RegExp( str2 + '/=^[0-9];[0-9]'),  new_values )
console.log(new_str);

http://jsfiddle.net/2b4xx/2/

Upvotes: 1

Views: 48

Answers (1)

anubhava
anubhava

Reputation: 785196

Your regex is wrong as there is no / in the input text and ^ is only valid at start and inside character class.

Try this:

var new_str = str.replace(new RegExp( str2 + ' *= *[0-9]+;[0-9]+' ), new_values );
console.log(new_str);

Upvotes: 1

Related Questions