簡體   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