Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Javascript replace with a loop

I'm try to replace all occurances wihtin a string with the array index value as below.

var str = '<a href="{0}" title="{1}">{1}</a>';
var params= [];
params.push('Url', 'TitleDisplay');

for (i in params) {
    var x = /'{' + i + '}'/g;
    str = str.replace(x, params[i]);
}

No matter what I do, I cannot seem to get it to work. Dropping the '/g' works with one match, but not all. I know this is basic but for the lide of me I cannot get it to work.

like image 968
Alex Guerin Avatar asked Dec 21 '22 19:12

Alex Guerin


2 Answers

Fiddle here

Code:

var rx = /{([0-9]+)}/g;
str=str.replace(rx,function($0,$1){return params[$1];});

The replace method loops through the string (because of /g in the regex) and finds all instances of {n} where n is a number. $1 captures the number and the function replaces {n} with params[n].

like image 141
Christophe Avatar answered Jan 01 '23 17:01

Christophe


try using this:

var x = new RegExp("\\{" + i + "\\}", "g");

instead of this:

var x = /'{' + i + '}'/g;
like image 21
GottZ Avatar answered Jan 01 '23 19:01

GottZ