jQuery替换变量不起作用

时间:2016-07-20 14:24:38

标签: javascript jquery

我正在尝试用data.replace替换字符串,如果使用硬代码或静态值,它的工作正常。但现在我想用循环替换多个值,但它不起作用。

我的代码:

for(var i = 0; i<words.length; i++){
    var r = words[i];
    data = data.replace(/\[(\[qid:{r})\]]/g, words[i]);
}

单词包含:

Array [ "hid_1", "hid_2", "hid_6", "hid_7" ]

我的数据是:

Site: [[qid:hid_1]]<br>

Block: [[qid:hid_2]]<br>

Nimewo kay la: [[qid:hid_6]]<br>

Latitude: [[qid:hid_7]]

是HTML内容。

我只需要变量:

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');

    }

3 个答案:

答案 0 :(得分:1)

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);
}

答案 1 :(得分:1)

您可以删除不属于的字符。然后,您不需要其他替换字符串数组。

修改

如果您的数据是一个长字符串,则可以执行以下操作:

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);

否则,如果您的数据在数组中,您可以这样做:

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);

答案 2 :(得分:0)

这是你在做什么的?看起来很好。

 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);

 }