假设我有以下内容:
var s = "This is a test of the battle system."
Run Code Online (Sandbox Code Playgroud)
我有一个数组:
var array = [
"is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"
]
Run Code Online (Sandbox Code Playgroud)
是否有一些函数或方法可以使我能够处理字符串s,使输出为:
var p = "This is <b>a test</b> of the <div style=\"color:red\">battle</div> system."
Run Code Online (Sandbox Code Playgroud)
基于数组中的任意元素?
请注意,数组元素应按顺序执行.因此,查看数组1中的第一个元素,找到字符串"s"中"替换"的正确位置.然后查看数组元素2,找到字符串"s"中"替换"的正确位置.
请注意,该字符串可以包含数字,括号和其他字符,如破折号(没有<>但是)
更新:在Colin DeClue发表评论之后,我想你想做一些与我原先想象的不同的事情.
以下是如何实现这一目标的方法
//your array
var array = [
"is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"
];
//create a sample span element, this is to use the built in ability to get texts for tags
var cElem = document.createElement("span");
//create a clean version of the array, without the HTML, map might need to be shimmed for older browsers with a for loop;
var cleanArray = array.map(function(elem){
cElem.innerHTML = elem;
return cElem.textContent;
});
//the string you want to replace on
var s = "This is a test of the battle system."
//for each element in the array, look for elements that are the same as in the clean array, and replace them with the HTML versions
for(var i=0;i<array.length;i++){
var idx;//an index to start from, to avoid infinite loops, see discussion with 6502 for more information
while((idx = s.indexOf(cleanArray[i],idx)) > -1){
s = s.replace(cleanArray[i],array[i]);
idx +=(array[i].length - cleanArray[i].length) +1;//update the index
}
}
//write result
document.write(s);
Run Code Online (Sandbox Code Playgroud)
工作示例:http://jsbin.com/opudah/9/edit
原始答案,如果这是你的意思毕竟
是.运用join
var s = array.join(" ");
Run Code Online (Sandbox Code Playgroud)