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"
[^\S\r\n]+
Not a non-whitespace char, not \r
and not \n
; one or more instances.
This will work, even on \t
.
var newstr = s.replace(/ +?/g, '');
Although in Javascript / /g
does match \t
, I find it can hide the original intent as it reads as a match for the space character. The alternative would be to use a character collection explicitly listing the whitespace characters, excluding \n
. i.e. /[ \t\r]+/g
.
var newString = s.replace(/[ \t\r]+/g,"");
If you want to match every whitespace character that \s
matches except for newlines, you could use this:
/[\t\v\f\r \u00a0\u2000-\u200b\u2028-\u2029\u3000]+/g
Note that this will remove carriage returns (\r
), so if the input contains \r\n
pairs, they will be converted to just \n
. If you want to preserve carriage returns, just remove the \r
from the regular expression.
Try this
var trimmedString = orgString.replace(/^\s+|\s+$/g, '') ;
This does the trick:
str.replace(/ /g, "")
and the space does NOT match tabs or linebreaks (CHROME45), no plus or questionmark is needed when replacing globally.
In Perl you have the "horizontal whitespace" shorthand \h to destinguish between linebreaks and spaces but unfortunately not in JavaScript.
The \t shorthand on the other hand IS supported in JavaScript, but it describes the tabulator only.
const str = "abc def ghi";
str.replace(/\s/g, "")
-> "abcdefghi"
try this '/^\\s*/'
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.
*optimisation by @Toto:
code.replace(/^\s+/gm, '')
精彩评论