2017-08-03 195 views
-4

例如,我有串如何解析字符串中的HTML標籤和內容?

'<p class="something">text goes here</p>' 

我想解析出來到每個標籤的陣列和內容,即:

['<p class="something">', 'text goes here', '</p>'] 
+3

不要使用正則表達式:https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Dai

+1

如果存在嵌套元素,您的程序應該如何運行?或CDATA部分(帶有未轉義的尖括號)?爲什麼選出'#text'節點而不是屬性和元素名稱? – Dai

+0

你會用什麼樣的數組?當然似乎不太實際。一個對象會更明智 – charlietfl

回答

0

您還沒有解釋使用這種情況下,但這個答案會提供相同的數據(數組中組織有點不同),如果需要,可以使用數據重新創建元素。

var test = "<p class='something'>text goes here</p>"; 
 

 
// Set up an element that can contain the parsed string 
 
var dummyElement = document.createElement("div"); 
 

 
// Parse/load the string into the element 
 
dummyElement.innerHTML = test; 
 

 
// Now we can extract metadata about the element and populate the array 
 
var htmlData = []; 
 

 
// Shortcut to element 
 
var el = dummyElement.firstChild; 
 

 
// Push node name into array: 
 
htmlData.push(el.nodeName); 
 

 
// Loop through attributes and put them into array: 
 
for(var x = 0; x < el.attributes.length; x++){ 
 
    htmlData.push(el.attributes[x].nodeName + "=" + el.attributes[x].nodeValue); 
 
} 
 

 
// Put element content (if it has any) into array 
 
htmlData.push(el.textContent); 
 

 
console.log(htmlData);

+0

當數組長度因屬性數量而異時,仍然很笨拙 - 但是的確回答了問題 – charlietfl

+0

@charlietfl即使在使用所有可能屬性的最常涉及的元素中,數組長度仍然可以很容易地處理JavaScript數組。 –

+0

噢,這不是問題。如果我是歐普,我會選擇一個對象,其中屬性是一個屬性(數組),標記名,內容等作爲其他道具。沒有提出答案的任何錯誤。它確實回答了直接的問題 – charlietfl

0

這不是解決你的問題的更好的方法,但可以幫助你。

const elements = [ 
 
    '<p id="x" required>Content X</p>', 
 
    '<p id="y" class="y">Content Y</p>', 
 
    '<a href="www.google.com">Google</a>' 
 
]; 
 

 
const parser = new DOMParser(); 
 

 
const result = elements 
 
.map(element => parser.parseFromString(element, "text/html")) 
 
.map(html => html.firstElementChild.children[1].children[0]) 
 
.map(child => { 
 
    const nodeName = child.nodeName.toLowerCase(); 
 
    const attrs = [...child.attributes] 
 
    .map(attr => { 
 
     if (attr.value === '') { 
 
     return attr.name; 
 
     } else if (attr.value.indexOf('"') > -1) { 
 
     return `${attr.name}='${attr.value}'`; 
 
     } else { 
 
     return `${attr.name}="${attr.value}"`; 
 
     } 
 
    }) 
 
    .join(' '); 
 
    
 
    return [ 
 
    `<${nodeName} ${attrs}>`, 
 
    child.textContent, 
 
    `</${nodeName}>` 
 
    ]; 
 
}); 
 

 
console.log('Result', JSON.stringify(result, null, 4));