2017-09-29 72 views
0

我有這樣的文字展開HTML標記,只保留第一級

"Welcome to my city. <span><span><span>Hello</span> my</span> good</span> friend" 

使用jQuery(或JavaScript)我想解開所有span標籤只保持第一的水平,我的意思是, 所需要的輸出將是:

"Welcome to my city. <span>Hello my good</span> friend" 

在此先感謝您。

+1

你想做到這一點在JavaScript?在預處理器中?服務器端?什麼?看起來像你已經解開他們自己:-) –

+1

我想你沒有看到標籤「JavaScript」和「jquery」 –

+0

你是對的,我錯過了那些。我的錯。 jQuery可能會讓我失望,但JavaScript仍然意味着預處理。 –

回答

0

如果您的文本是一個字符串裏,你可以使用正則表達式是這樣的:

var string = 'Welcome to my city. <span id="test"><span><span class="test2">Hello</span> my</span> good</span> friend'; 
 
var regex = /<span.*?>(.*)<\/span>/g; 
 

 
var insideOfSpan = regex.exec(string); 
 

 
var strippedSpan = insideOfSpan[1].replace(/<\/?span.*?>/g, ''); 
 

 
string = string.replace(/(<span.*?>).*(<\/span>)/, '$1' + strippedSpan + '$2'); 
 
console.log(string);

+0

謝謝。但如果span標籤包含更多信息,如類,id, –

+0

我更新了我的答案,現在它應該與屬性一起工作,它將無法正常工作。 – Walk

+1

試圖用RegExp解析HTML是[幾乎從來不是一個好主意](https://blog.codinghorror.com/parsing-html-the-cthulhu-way/),它太脆弱了,可以很容易地破解,特別是如果你會得到一些格式不正確或惡意的HTML。 –

1

你可以通過將其注入的元素解析HTML,然後抓取其子節點,以原樣輸出文本節點,並通過讀取.textContent並用此替換.innerHTML來轉換頂級元素的內容。

function topLevelNodesOnly(html) { 
 
    let div = document.createElement('div'); 
 
    div.innerHTML = html; 
 

 
    let out = ''; 
 
    // using [...someVar] converts array-like things into real arrays 
 
    [...div.childNodes].forEach((node) => { 
 
    // if the node is a text node, add it's text to the output string 
 
    if (node.nodeType === 3) { 
 
     out += node.wholeText; 
 
    } else { 
 
     // if it is anything else, replace it's contents with the text 
 
     // of it's contents 
 
     node.innerHTML = node.textContent; 
 
     // add the html that generated to the output 
 
     out += node.outerHTML; 
 
    } 
 
    }); 
 

 
    return out; 
 
} 
 

 
console.log(topLevelNodesOnly(`Welcome to my city. <span class="hello"><span><span>Hello</span> my</span> good</span> friend`));