up vote 3 down vote favorite
3
share [fb]

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]

link|improve this question

69% accept rate
Out of curiosity, what about just using variables? – hookedonwinter Aug 4 '10 at 22:32
The text is being take from a textbox.value – kalpaitch Aug 4 '10 at 22:34
ah i see. noted. – hookedonwinter Aug 4 '10 at 22:42
Just to clarify - the format string ("Dear [blah] etc [blah]") is taken from a text box, or the values you fill in that string with are taken from a text box? – Merlyn Morgan-Graham Aug 4 '10 at 22:54
@Merlyn Morgan-Graham: The entire string is take from the value of the text box. The vales 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 – kalpaitch Aug 4 '10 at 22:59
feedback

2 Answers

up vote 5 down vote accepted

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++];
});
link|improve this answer
thank you for that reminder about the white space. – kalpaitch Aug 4 '10 at 22:44
unfortunately I can't match by the content between the brackets as this may change – kalpaitch Aug 4 '10 at 22:45
cheers perfect, makes sense and works – kalpaitch Aug 4 '10 at 23:02
feedback

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 )​
link|improve this answer
thats the issue, these bracketed values will change, so I need a way to replace them by index/order – kalpaitch Aug 4 '10 at 22:42
gotchya. then in that case, @Sean's answer > mine. – hookedonwinter Aug 4 '10 at 22:43
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.