您好,我希望幫助創建一個替換所有 html 標籤的正則表達式,但是當結束 div 和開始 div 彼此相鄰時,它會添加一個空格,例如
此<b>is</b> <div>a</div><div>test</div>
這是一個測試
#我目前的正規表示式是/(<([^>] )>)/ig 它將取代所有html 標籤,但我想知道每當有一個結束div 和接下來的開始div 時如何新增一個空格彼此。
我嘗試使用 /(<([^>] )>)/ig 來取代有效的 html,但當它們彼此相鄰時,我需要有關 div 間距的幫助
P粉2960800762024-04-03 10:33:20
JS 內建了對 HTML 解析的支援。使用它來代替:
function getSpaceSeparatedText(html) { // Create an element and use it as a parser let parser = document.createElement('div'); parser.innerHTML = html; const result = []; for (const node of parser.childNodes) { // Get the trimmed text const text = node.textContent.trim(); // If text is not empty, add it to result if (text) { result.push(text); } } return result.join(' '); }
嘗試一下:
console.config({ maximize: true }); function getSpaceSeparatedText(html) { let parser = document.createElement('div'); parser.innerHTML = html; const result = []; for (const node of parser.childNodes) { const text = node.textContent.trim(); if (text) { result.push(text); } } return result.join(' '); } const html = ` This isatest`; console.log(getSpaceSeparatedText(html));
sssccc