如何替换js中的文本?

时间:2013-03-27 21:04:38

标签: javascript html

假设我有以下内容:

var s = "This is a test of the battle system."

我有一个数组:

var array = [
"is <b>a test</b>",
"of the <div style=\"color:red\">battle</div> system"
]

是否有一些功能或方法可以使我能够处理字符串s,使输出为:

var p = "This is <b>a test</b> of the <div style=\"color:red\">battle</div> system."

基于数组中的任意元素?

请注意,数组元素应按顺序执行。因此,查看数组1中的第一个元素,找到字符串“s”中“替换”的正确位置。然后查看数组元素2,找到字符串“s”中“替换”的正确位置。

请注意,字符串可以包含数字,括号和其他字符,例如破折号(不是&lt;&gt;尽管)

2 个答案:

答案 0 :(得分:6)

更新:在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);

工作示例:http://jsbin.com/opudah/9/edit


原始答案,如果这是你的意思

是。使用join

var s = array.join(" ");

Here is a working example in codepen

答案 1 :(得分:0)

<击> 我想你有一对original --> replacement对。 要从HTML中提取文本,可能适合您的技巧实际上是创建DOM节点,然后提取文本内容。

获得文本后,可以将replace方法与正则表达式一起使用。 一个令人讨厌的事情是,搜索精确字符串并不简单,因为Javascript中没有escape预定义函数:

function textOf(html) {
    var n = document.createElement("div");
    n.innerHTML = html;
    return n.textContent;
}

var subs = ["is <b>a test</b>",
            "of the <div style=\"color:red\">battle</div> system"];

var s = "This is a test of the battle system"

for (var i=0; i<subs.length; i++) {
    var target = textOf(subs[i]);
    var replacement = subs[i];
    var re = new RegExp(target.replace(/[\\[\]{}()+*$^|]/g, "\\$&"), "g");
    s = s.replace(re, replacement);
}

alert(s);