views:

37

answers:

2

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]

+5  A: 

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++];
});
Sean
thank you for that reminder about the white space.
kalpaitch
unfortunately I can't match by the content between the brackets as this may change
kalpaitch
cheers perfect, makes sense and works
kalpaitch
+3  A: 

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 )​
hookedonwinter
thats the issue, these bracketed values will change, so I need a way to replace them by index/order
kalpaitch
gotchya. then in that case, @Sean's answer > mine.
hookedonwinter