2013-03-27 37 views
1

假設我有以下幾點:如何替換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」中「替換」的正確位置。

注意,字符串可以包含數字,括號和其他字符,如破折號(無<>雖然)

+1

我不知道如何給出了錯誤的語法高亮這些錯誤不會馬上變得明顯。即使我不明白代碼,我仍然可以說出事情是錯的。 – elclanrs 2013-03-27 21:07:28

回答

6

更新:科林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

我不認爲這是海報想要的。我認爲海報要用's'開始,使用'array'來處理它,輸出最後一個'''。 – 2013-03-27 21:09:50

+0

科林是對的,這不是我要找的。我期待將「數組」中的所有元素應用到字符串s以實現所需的結果字符串。 – Rolando 2013-03-27 21:16:25

+0

@ColinDeClue我很抱歉,這是我的不好。查看最近的編輯 – 2013-03-27 21:22:47

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);