[英]Append closing then opening HTML tag with Javascript/Jquery
[英]Remove the spaces between the closing and opening tag in html with JavaScript
我已經嘗試過 Stackoverflow 中的所有解決方案,但它並沒有真正奏效。
輸入 1: ' <ul> <li>Lorem Delor </li> </ul> '
預期 Output 1: '<ul><li>Lorem Delor</li></ul>'
輸入 2: ' <ul> <li>Lorem <b>Ipsum</b> Delor </li> </ul> '
預期 Output 2: '<ul><li>Lorem <b>Ipsum</b> Delor</li></ul>'
Stackoverflow 中的解決方案: '<ul><li>Lorem<b>Ipsum</b>Delor</li></ul>'
輸入 3:
Stack
overflow
預期 Output 3:
Stack
overflow
許多正則表達式解決方案忽略內聯元素。 這就是頁面上的單詞變得統一的原因(輸入 2)。 我想知道是否真的有一個明確的解決方案。
重要提示:這應該只影響 html 輸入,而不是純文本。 (輸入 3)
您可以使用這兩個刪除行尾和空格的正則表達式。
const input = ` <ul> <li>Lorem Delor </li> <li>Lorem Delor </li> </ul> `; const output = input // remove eols between tags.replace(/\>[\r\n ]+\</g, "><") // remove spaces between tags.replace(/(<.*?>)|\s+/g, (m, $1) => $1 || ' ').trim(); console.log(output);
在您的問題示例中,您想刪除標簽結尾之前的每個空格,但我發現它不需要。 可以有意放置該空間(它可以是內聯元素,您可能希望保留該空間)。 因此,如果之前有一個或多個空格,則第二個常規在結束標記之前留下一個空格。 如果您真的想刪除所有空格(您不應該),只需將' '
替換為''
。
使用正則表達式/\s+/gim
刪除多個空格。
txt.replace(/\s+/gim, ' ')
使用正則表達式/>\s+</gim
刪除> <
之間的空格。
txt.replace(/>\s+</gim, '><')
代碼:
var input1 = ' <ul> <li>Lorem Delor </li> </ul> ';
var input2 = ` <ul> <li>Lorem <b>Ipsum</b> Delor </li> </ul> `;
console.log(input1.replace(/\s+/gim, ' ').trim().replace(/>\s+</gim, '><'));
console.log(input2.replace(/\s+/gim, ' ').trim().replace(/>\s+</gim, '><'));
Output:
'<ul><li>Lorem Delor </li></ul>'
'<ul><li>Lorem <b>Ipsum</b> Delor </li></ul>'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.