replace all occurrences of a character in a javascript string

Asked

Viewed 981 times

6

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

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

Somebody help me get through this problem?

1 answer

6


You don’t need to use regex you can use .split()/.join() which separates the string by this character and then joins back together 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 have to use the constructor new RegExp();:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.