繁体   English   中英

如何替换js中的文本?

[英]How to replace text in js?

假设我有以下内容:

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”。

请注意,该字符串可以包含数字,方括号和其他字符,例如破折号(尽管没有<>)

更新:在科林·德克鲁(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(" ");

这是Codepen中的一个工作示例

我想您有一组 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM