在动态字符串前后插入字符串

时间:2016-05-23 09:31:49

标签: javascript regex

假设我有以下字符串..

string = 'bla bla bla data-id="34232" bla bla bla bla data-id="457667" bla bla bla bla bla bla data-id="45454" bla bla'

我需要替换成以下字符串..

string = 'bla bla bla <div data-id="34232"></div> bla bla bla bla <div data-id="457667"></div> bla bla bla bla bla bla <div data-id="45454"></div> bla bla'

我这样做..

string.match(/data-id="(.*?)"/g);
// ["data-id="34232"", "data-id="457667"", "data-id="45454""]
之后,我不知道如何做到这一点......

谢谢你的帮助..

4 个答案:

答案 0 :(得分:2)

使用 replace() 执行字符串替换,并在替换字符串中使用$& which helps to inserts the matched substring

&#13;
&#13;
var str = 'bla bla bla data-id="34232" bla bla bla bla data-id="457667" bla bla bla bla bla bla data-id="45454" bla bla';

console.log(
  str.replace(/data-id=".*?"/g, '<div $&></div>')
)
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试此操作(使用拆分并对您的正则表达式进行微小修改

string = string.split(/(data-id=".*?)"/).map(function(val, index){ if ( index % 2== 1 ){ val = "<div " + val + "></div>" } return val; }).join("");

<强>样本

var string = 'bla bla bla data-id="34232" bla bla bla bla data-id="457667" bla bla bla bla bla bla data-id="45454" bla bla'
string = string.split(/(data-id=".*?)"/).map(function(val, index){ if ( index % 2== 1 ){ val = "<div " + val + "></div>" } return val; }).join("");
alert(string);

答案 2 :(得分:0)

看看这个Regex Demo

您也可以捕获data-id=及其中的值,并在替换中使用它。

&#13;
&#13;
var s = 'bla bla bla data-id="34232" bla bla bla bla data-id="457667" bla bla bla bla bla bla data-id="45454" bla bla'
console.log(s.replace(/(data-id="\d+")/g, '<div $1></div>'));

// "bla bla bla <div data-id="34232"></div> bla bla bla bla <div data-id="457667"></div> bla bla bla bla bla bla <div data-id="45454"></div> bla bla"
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用String.replace函数的解决方案(带有“replacer”功能):

var str = 'bla bla bla data-id="34232" bla bla bla bla data-id="457667" bla bla bla bla bla bla data-id="45454" bla bla',
    wrapped = str.replace(/data-id=\"[^"]+\"/g, function(m){
        return "<div " + m + "></div>";
    });

console.log(wrapped);
// "bla bla bla <div data-id="34232"></div> bla bla bla bla <div data-id="457667"></div> bla bla bla bla bla bla <div data-id="45454"></div> bla bla"