Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for removing whitespaces

I have some text which looks like this -

"    tushar is a good      boy     "

Using javascript I want to remove all the extra white spaces in a string.

The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -

"tushar is a good boy"

I am using the following code at the moment-

str.replace(/(\s\s\s*)/g, ' ')

This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.

like image 756
tusharmath Avatar asked Aug 05 '13 19:08

tusharmath


People also ask

How do you remove whitespaces from a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

Which commands are there to remove whitespaces?

To remove whitespaces from your document, you can use various tools such as awk, sed, cut, and tr. In some other articles, we have discussed the use of awk in removing the whitespaces. In this article, we will be discussing the use of sed for removing whitespaces from the data.

How do I trim a whitespace in regex?

Trimming WhitespaceSearch for [ \t]+$ to trim trailing whitespace. Do both by combining the regular expressions into ^[ \t]+|[ \t]+$. Instead of [ \t] which matches a space or a tab, you can expand the character class into [ \t\r\n] if you also want to strip line breaks. Or you can use the shorthand \s instead.

What is the regex for whitespace?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.


1 Answers

This can be done in a single String#replace call:

var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

// gives: "tushar is a good boy"
like image 61
anubhava Avatar answered Sep 20 '22 15:09

anubhava