views:

140

answers:

6

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  A: 

Try this

var trimmedString = orgString.replace(/^\s+|\s+$/g, '') ;
Chinmayee
you can do it without regular expression also, orgString.split(' ').join('');
Chinmayee
@Chinmayee, `split(' ')` only removes spaces, not tabs or other whitespace.
Tatu Ulmanen
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 !!
sat
var trimmedString = orgString.replace(/ /g, ''); is the right expression Earlier expression was trimming spaces only at beginning and end of the line
Chinmayee
@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 !!
sat
A: 

Check here

org.life.java
A: 

try this '/^\\s*/'

Paniyar
+1  A: 

This will work, even on \t.

var newstr = s.replace(/ +?/g, '');
Ruel
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.
tKe
That shouldn't be working on tabs.
Matthew Crumley
@Matthew, Tested. It is.
Ruel
@Ruel: Everywhere I've tested it, tabs don't get replaced.
Matthew Crumley
+2  A: 

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

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.

Matthew Crumley