replace all occurrences of a character in a string with javascript

5

I need to replace all occurrences of these 2 "_1" characters in a string with "_2", but Regex does not accept putting a variable there.

var current_registration_number = 1;
html = html.replace(/\_{current_registration_number}/g, '_'+next_registration_number);

Does anyone help me to overcome this problem?

    
asked by anonymous 27.07.2016 / 11:34

1 answer

5

You do not need to use regex, you can use .split() / .join() that separates the string with that character and then returns to join by inserting the new character as a union of these parts:

html = html.split('_' + current_registration_number ).join('_' + next_registration_number);

To use regex you must use the constructor new RegExp(); :

var regex = new RegExp('\_' + current_registration_number, 'g');
html = html.replace(regex, '_' + next_registration_number);

Notice that you have to use \ twice as this string that you pass to the constructor "escapes" in the conversion.

    
27.07.2016 / 11:43