Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace() regex by index number

I have the following string and regex:

var string = "Dear [to name], [your name] has decided to share this [link]"; 
var patt = /\[+[A-Za-z0-9]+\]/;

I want to be able to change each of the bracketed variables with dynamic input. How would I use match() or replace() to target the 1st, 2nd and 3rd occurrences of this regex?

EDIT: At the moment if I do something like document.write(body.match(patt)); it will match only the last one [link]

EDIT: The entire string is take from the value of a text box. The values for each of the brackets are taken from other text inputs and need to be inserted into the string before the text is put back into the text box.

like image 447
kalpaitch Avatar asked Aug 04 '10 22:08

kalpaitch


2 Answers

Use a function as the second argument to the replace method:

var replacement = { "to name": "Joe", "your name": "Fred", "link": "foo" };

string = string.replace(/\[([^\]]+)\]/g, function (_, group) {
    return replacement[group];
});

Oh, and the reason your pattern is only matching the [link] text is because it allows only alphanumeric characters between brackets, not spaces.

EDIT: If the content of the brackets is unimportant, and you just want to replace them in order, use an array instead of a hash:

var replacement = [ "Joe", "Fred", "foo" ];
var index = 0;
string = string.replace(/\[[^\]]+\]/g, function () {
    return replacement[index++];
});
like image 152
Sean Avatar answered Sep 20 '22 00:09

Sean


Assuming those bracketed items are always the same, you don't have to use regex at all.

var string = "Dear [to name], [your name] has decided to share this [link]"; 
var name = 'Bob';
var your_name = 'Jacob';
var link = 'http://google.com';

string = string.replace( '[to name]', name ).replace( '[your name]', your_name ).replace( '[link]', link )

alert( string )​
like image 26
hookedonwinter Avatar answered Sep 24 '22 00:09

hookedonwinter