您好,我希望帮助创建一个替换所有 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