29

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"
1
  • Can you show us your C# solution? Most common C# regular expressions should work fine in JavaScript (including \t). Commented Oct 6, 2010 at 13:30

10 Answers 10

31
[^\S\r\n]+

Not a non-whitespace char, not \r and not \n; one or more instances.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow. very neat. I wonder why this is not popular way to exclude specific characters.
This is a wonderful answer that enables a whole class of "this, except that" regular expressions.
16

This will work, even on \t.

var newstr = s.replace(/ +?/g, '');

7 Comments

there is no need for the + or ?, just s.replace(/ /g,'') would suffice. I personally don't like the fact that / /g matches tabs as this to me reads as "matches the space character". /[ \t\r]/g would match spaces, tabs and character returns and is more readable in it's intent.
Everywhere I've tested it, tabs don't get replaced.
Are you sure about / +?/g woking on \t? 'Cuz I get [1,1] from a="\t";b=a.replace(/ +?/g, '');console.log([a.length,b.length]);, on Firefox8.
And "\t".replace(/ +?/g,'').length; does output 1 on Chrome15's console.
This is 1) not an answer (since it is asked to remove ALL whitespace), 2) misleading, since / +?/g newer gonna catch tabs 3) overcomlicated (why ??) and inefficient (in case of 10 spaces makes 10 replaces instead of a single one). Hence, the answer is useless and harmful.
|
12

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

Comments

7

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.

2 Comments

How does that compare to [^\S\r\n]+?
@trusktr That should behave identically. It might be slightly confusing since there's a hidden double negative (not non-whitespace or \r or \n), but it's shorter and a lot easier to remember.
0

Try this

var trimmedString = orgString.replace(/^\s+|\s+$/g, '') ;

5 Comments

you can do it without regular expression also, orgString.split(' ').join('');
split(' ') only removes spaces, not tabs or other whitespace.
split and join serves my purpose , but the first one does not seem to work !! e.g. var s = "this\n is a te st" using regexp method I expect it to return "this\nisatest" Isn't it suppose to work that way !!
var trimmedString = orgString.replace(/ /g, ''); is the right expression Earlier expression was trimming spaces only at beginning and end of the line
@Tatu -- What kind of whitespace wont work with split ? because I tried with tabs and used split and join method, it worked in removing those spaces !!
0

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.

Comments

0
const str = "abc def ghi"; 

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

-> "abcdefghi"

2 Comments

Can you please elaborate with some explanation. So that the answer would be useful for the community.
This solution would also delete \n, which the OP didn't want to
0
  • Will remove all whitespace: blank,\t,\r,\f,\v except newline: assuming that only \n (line feed) is newline and not \r (carriage return).
  • If you want to keep \r too, just add \r behind \n in the code below. Because depending on the operating system (windows, mac, linux) the newline will be \n or \r or \r\n
  • \S matches any non-whitespace character (equivalent to [^\r\n\t\f\v ])
const text = "This is a  \n test string \t with  \n whitespace.";
const result = text.replace(/[^\S\n]+/g, '');
console.log(result);
//result: 
//Thisisa
//teststringwith
//whitespace.

Comments

-1

try this '/^\\s*/'

Comments

-1

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

1 Comment

[^\S]* is strictly equal to \s*, the whole regex is equivalent to ^\s+, it matches all kind of spaces (including linebreak that is not wanted) at the beginning of a string, see: regex101.com/r/Q5tJYZ/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.