Search code examples
javascriptregextrim

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


how can I turn this

\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 

into this

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

using javascript ?

I've tried following code. but could not get this to work

.replace(/\r?\n?\s+/g, '').trim();

Solution

  • Your regexes are incorrect.

    Example output from 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>'
    

    You should get the gist how to add more cleanup code...

    In short: don't try to squeeze everything into one regex.