我在数组中有一些字符串值
var anchors = [
"Can",
", please?"
];
我有类似下面示例的字符串
<anchor>0</anchor> you repeat that<anchor>1</anchor>
我想在下面的
中构建结果字符串Can <drop></drop> <drop></drop> <drop></drop>, please?
I want to replace all the <anchor>0</anchor> to the words in the given array and words into <drop></drop> tag
有人请帮我用javascript字符串操作或正则表达式
来构造生成的字符串答案 0 :(得分:2)
您可以尝试以下内容
var myarray =[ "Can",",please?" ];
var inputstring ="<anchor>0</anchor> you repeat that <anchor>1</anchor>"
var len=inputstring.split(" ").length-1
var inputstring1;
for(var i=0;i<=myarray.length;i++)
{
inputstring1 += inputstring.replace("<anchor>"+i+"</anchor>",myarray[i])
}
var inputstring2=inputstring
for(var i=0;i<=myarray.length;i++)
{
inputstring2 = inputstring2.replace("<anchor>"+i+"</anchor>","")
}
myarrayremovedelemets=inputstring2.split(" ")
myarrayremovedelemets.push.apply(myarrayremovedelemets, myarray);
alert(myarrayremovedelemets);
然后将inputstring1替换为<drop></drop>
答案 1 :(得分:1)
您可以在callback function
使用以下逻辑:
<强>输出:强>
Can <drop></drop> <drop></drop> <drop></drop>, please?
<强>代码:强>
var anchors = [
"Can",
", please?"
];
var replaceCallback = function(match, g1, g2) {
if(g1 != null) return anchors[g1];
if(g2 != null) return "<drop></drop>";
return match;
}
var str = "<anchor>0</anchor> you repeat that<anchor>1</anchor>";
str = str.replace(/<anchor>(\d+)<\/anchor>|(\w+)/g, replaceCallback);
alert(str);
修改:更新了正则表达式:
/<anchor>(\d+)<\/anchor>|((?:(?!<anchor>)\S)+)/g
修改:single
:
/<(?:anchor|single)>(\d+)<\/(?:anchor|single)>|((?:(?!<(?:anchor|single)>)\S)+)/g