日期:2014-05-16  浏览次数:20355 次

JS正则批量替换,来正则高手


JScript code

var hashJson = {"[a]":"abss","[b]":"ffe","[c]":"assxx","[d]":"hhhss"};
var testStr ="[a]dbciidlsoog[b]dddd[d]";
var front="<input value=\"";
var back="\"/>";



上面3个变量
我要把 testStr的串取出来将对应hashJson的Key换成加标示Value。
例如: 将testStr的值替换成 "<input value=\"abss\"/>dbciidlsoog<input value=\"ffe\"/>dddd<input value=\"hhhss\"/>";
比较麻烦,看看有没有大牛了


------解决方案--------------------
JScript code
var hashJson = {"[a]":"abss","[b]":"ffe","[c]":"assxx","[d]":"hhhss"};
var testStr ="[a]dbciidlsoog[b]dddd[d]";
var front="<input value=\"";
var back="\"/>";
testStr=testStr.replace(/(\[[a-z]+\])/ig,function($1) {return front+hashJson[$1]+back; })

alert(testStr)

------解决方案--------------------
JScript code
var hashJson = {"[aa]":"1","[b]":"2","[c]":"3","[d]":"4"};
var testStr ="[aa] x [b] y [d] z";
var re=/([\[](\S+)[]])/g;
testStr=testStr.replace(re,function(a){return hashJson[a]});
alert(testStr);

------解决方案--------------------
探讨

引用:
JScript code
var hashJson = {"[a]":"abss","[b]":"ffe","[c]":"assxx","[d]":"hhhss"};
var testStr ="[a]dbciidlsoog[b]dddd[d]";
var front="<input value=\"";
var back="\"/>";
testStr=t……

------解决方案--------------------
探讨

JScript code
var hashJson = {"[a]":"abss","[b]":"ffe","[c]":"assxx","[d]":"hhhss"};
var testStr ="[a]dbciidlsoog[b]dddd[d]";
var front="<input value=\"";
var back="\"/>";
testStr=testStr.replace(/(\……

------解决方案--------------------
var hashJson = {"[aa]":"1","[b]":"2","[c]":"3","[d]":"4"};
var testStr ="[aa] x [b] y [d] z";
var re=/([\[](\S+)[]])/g;
testStr=testStr.replace(re,function(a){return hashJson[a]});
alert(testStr);


------解决方案--------------------
JScript code

    var hashJson = {"[a]":"abss","[b]":"ffe","[c]":"assxx","[d]":"hhhss"};
    var testStr ="[a]dbciidlsoog[b]dddd[d]";
    var front="<input value=\"";
    var back="\"/>";
    var re = /\[\w+\]/gi;
    testStr = testStr.replace(re, function($){
        return front+'\\'+hashJson[$]+'\\'+back;
    });
    alert(testStr);

------解决方案--------------------
JScript code
var hashJson = {"[a]":"abss","[b]":"ffe","[c]":"assxx","[d]":"hhhss"}; 
var testStr ="[a]dbciidlsoog[b]dddd[d]"; 
var front="<input value=\""; var back="\"/>"; 
testStr=testStr.replace(/\[[^\]]+\]/g,function($0) {return front+hashJson[$0]+b