Is there a JavaScript regular expression to remove all whitespace except newline?

Viewed 42279

How do I remove white spaces in a string but not new line character in JavaScript. I found a solution for C# , by using \t , but it's not supported in JavaScript.

To make it more clear, here's an example:

var s = "this\n is a\n te st"

using regexp method I expect it to return

"this\nisa\ntest"
9 Answers
const str = "abc def ghi"; 

str.replace(/\s/g, "")

-> "abcdefghi"

code.replace(/^\s[^\S]*/gm, '')

works for me on text like:

    #set($todayString = $util.time.nowEpochMilliSeconds())
    #set($pk = $util.autoId())
    $util.qr($ctx.stash.put("postId", $pk))

and removes the space/tabs before the first 3 lines with removing the spaces in the line.

enter image description here

*optimisation by @Toto: code.replace(/^\s+/gm, '')

Related