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

remove extra space, line breaks and $nbsp from a string javascript

我怎样才能把这个

\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();

您的正则表达式不正确。

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>'

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

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

我认为这会成功:

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

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

它会尊重 html 标记内的所有内容,但会擦除标记外的每个 space、制表符、回车符 return 等。

您可以看到它正在运行 HERE

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

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

之前的任何 space

&nbsp; - 麦克西斯 &nbsp;.

([<>]\s+) - 匹配任何 <> 后跟 space.

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, "")

console.log(op)

您可以使用一个正则表达式来完成:/\r?\n?\s\s+|\s+(?=>)|&nbsp;/g

这里唯一可能的问题是它不会像 < !doctype> 那样删除 < 之后的单个空格,但到目前为止我们得到的答案也没有。如果 js 支持 positive lookbehinds,您可以覆盖它,只需将 |(?<=<)\s+ 添加到正则表达式。

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