从字符串 javascript 中删除多余的空格、换行符和 $nbsp

问题描述 投票:0回答:4

我该如何转动它

\n            <!DOCTYPE html >\n            <html>\n                <body>\n                <p>test&nbsp;&nbsp;</p>\n                <select multiple=\"multiple\">\n                    <option value=\"1\" correct=\"true\">red</option><option value=\"2\" correct=\"false\">Blue</option>\n                </select>\n                <p visible-if=\"correct\">Yeah correct</p>\n                <p visible-if=\"wrong\">Wrong dude</p>\n                </body>\n            </html>\n 

进入这个

<!DOCTYPE html><html><body><p>test</p><select multiple="multiple"> <option value="1" correct="true">red</option><option value="2" correct="false">Blue</option></select><p visible-if="correct">Yeah correct</p><p visible-if="wrong">Wrong dude</p></body></html>

使用javascript

我尝试过以下代码。但无法让它发挥作用

.replace(/\r?\n?\s+/g, '').trim();
javascript regex trim
4个回答
1
投票

您的正则表达式不正确。

Node.js CLI 的输出示例:

> "\n ... your string here ... </html>\n".replace(/[\r\n]/g, '').replace(/\s+/g, ' ').replace(/ >/g, '>').replace(/> </g, '><').trim()
'<!DOCTYPE html><html><body><p>test&nbsp;&nbsp;</p><select multiple="multiple"><option value="1" correct="true">red</option><option value="2" correct="false">Blue</option></select><p visible-if="correct">Yeah correct</p><p visible-if="wrong">Wrong dude</p></body></html>'

您应该了解如何添加更多清理代码的要点...

简而言之:不要试图将所有内容都压缩到一个正则表达式中。


1
投票

我认为这会成功:

let result = null;
let input = `     <!DOCTYPE html >  
<html>             <body>`;

result = input.replace(/\s+((?=\<)|(?=$))/g, '');

它将尊重 html 标记内的所有内容,但会删除其外部的每个空格、制表符、回车符等。

您可以在此处看到它的工作原理。


1
投票

这个正则表达式会有所帮助。

\s+([<>])
- 匹配
<
>

之前的任何空格

&nbsp;
- Macthes
&nbsp;

([<>]\s+)
- 匹配任何
<
>
后跟空格。

let str = `'\n            <!DOCTYPE html >\n            <html>\n                <body>\n                <p>test&nbsp;&nbsp;</p>\n                <select multiple=\"multiple\">\n                    <option value=\"1\" correct=\"true\">red</option><option value=\"2\" correct=\"false\">Blue</option>\n                </select>\n                <p visible-if=\"correct\">Yeah correct</p>\n                <p visible-if=\"wrong\">Wrong dude</p>\n                <  /body>\n            </html>\n';`

let op = str.replace(/\s+([<>])|&nbsp;|([<>])\s+/g, "$1$2")

console.log(op)


1
投票

您可以使用单个正则表达式来完成此操作:

/\r?\n?\s\s+|\s+(?=>)|&nbsp;/g

这里唯一可能的问题是,它不会像

<
中那样删除
< !doctype>
之后的单个空格,但到目前为止我们在这里得到的答案也没有。如果js支持正向后看,你就可以覆盖它,只需将
|(?<=<)\s+
添加到正则表达式即可。

顺便说一句,这是测试正则表达式的好地方:https://regexr.com

© www.soinside.com 2019 - 2024. All rights reserved.