2017-01-06 102 views
0

我想替換字符串中的一些文本,該字符串表示一個div標籤,該標籤可能包含也可能不包含樣式和類屬性。例如,如何使用正則表達式替換標籤之間的文本

var s = "<div style='xxx' class='xxx'>replaceThisText<div> 

如果只是標籤,我相信我可能只是這樣做:

str = str.replace(/<div>[\s\S]*?<\/div>/, '<div>' + newText+ '<\/div>'); 

但是我怎麼拿的屬性考慮?

+0

解析成DOM元素然後改變'.innerHTML '或'.textContent'。 –

+1

[必填的鏈接到着名的StackOverflow答案。](http://stackoverflow.com/a/1732454/1954610) –

回答

2

用您的字符串生成一個臨時元素作爲HTML內容,然後獲取其中的div以在更新內容後更新內容獲取臨時元素的HTML。

var s = "<div style='xxx' class='xxx'>replaceThisText<div>"; 
 

 
// create a temporary div element 
 
var temp = document.createElement('div'); 
 

 
// set content as string 
 
temp.innerHTML = s; 
 

 
// get div within the temporary element 
 
// and update the content within the div 
 
temp.querySelector('div').innerHTML = 'newText'; 
 

 
// get back the current HTML content in the 
 
// temporary div element 
 
console.log(temp.innerHTML)

爲什麼不能正則表達式?

RegEx match open tags except XHTML self-contained tags

Using regular expressions to parse HTML: why not?

+0

除了使用'querySelector'外,'temp.firstChild.innerHTML ='newText''怎麼辦? –

+0

@SpencerWieczorek:如果內容中沒有主要的空白或文本,那也可以,否則它可能是textNode –

0

正則表達式將永遠是一個很好的決定,解析HTML 內容
考慮使用DOMParser對象下面短溶液(對於支持DOMParser執行瀏覽器,見compatibility table):

var s = "<div style='xxx' class='xxx'>replaceThisText<div>", 
 
    tag = (new DOMParser()).parseFromString(s, 'text/html').querySelector('.xxx'); 
 

 
tag.textContent = 'newText'; // replacing with a new text 
 
console.log(tag.outerHTML); // outputs the initial tag representation with replaced content

https://developer.mozilla.org/ru/docs/Web/API/DOMParser

相關問題