Reputation: 622
I am trying to replace string with data.replace, its working fine if using hard code or static value. But now i want to replace multiple values with loop but its not working.
My Code:
for(var i = 0; i<words.length; i++){
var r = words[i];
data = data.replace(/\[(\[qid:{r})\]]/g, words[i]);
}
Words contains:
Array [ "hid_1", "hid_2", "hid_6", "hid_7" ]
and my data is:
Site: [[qid:hid_1]]<br>
Block: [[qid:hid_2]]<br>
Nimewo kay la: [[qid:hid_6]]<br>
Latitude: [[qid:hid_7]]
its an HTML content.
i just need variable here:
for(var i = 0; i<words.length; i++){
var r = words[i];
data = data.replace(/\[(\[qid:hid_1)\]]/g, 'test');
//data.replace(/\[(\[qid:{r})\]]/g, 'test');
}
Upvotes: 0
Views: 355
Reputation: 18908
You could just remove the characters that don't belong. Then, you don't need the other array of replacement strings.
EDIT
If your data is one long string, you can do the following:
var data = 'Site: [[qid:hid_1]]<br> Block: [[qid:hid_2]]<br> Nimewo kay la: [[qid:hid_6]]<br> Latitude: [[qid:hid_7]]';
data = data.replace(/\[\[qid:(.*?)]](?:<br>)?/g, '$1');
console.log(data);
Otherwise, if your data is in an array, you could do this:
var strings = [
'Site: [[qid:hid_1]]<br>',
'Block: [[qid:hid_2]]<br>',
'Nimewo kay la: [[qid:hid_6]]<br>',
'Latitude: [[qid:hid_7]]'
];
strings = strings.map(function(string) {
return string.replace(/\[.*?:([^\]]*).*/, '$1')
});
console.log(strings);
Upvotes: 1
Reputation: 596
var words = [ "hid_1", "hid_2", "hid_6", "hid_7" ];
var data = "Site: [[qid:hid_1]]<br>\
Block: [[qid:hid_2]]<br>\
Nimewo kay la: [[qid:hid_6]]<br>\
Latitude: [[qid:hid_7]]";
for(var i = 0; i<words.length; i++){
var r = words[i];
var reg = new RegExp('\\[\\[qid:' + r +'\\]\\]');
data = data.replace(reg, r);
}
Upvotes: 1
Reputation: 1329
is this what you are doing? Is seems fine.
data =["Site: [[qid:hid_1]]",
"Block: [[qid:hid_2]]<br>",
"Nimewo kay la: [[qid:hid_6]]",
"Latitude: [[qid:hid_7]]" ];
var words = [ "hid_1", "hid_2", "hid_6", "hid_7" ];
for(var i = 0; i<words.length; i++){
var r = data[i];
r = r.replace(/\[(\[qid:\w+)\]]/g, words[i]);
console.log(r);
}
Upvotes: 0