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.
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.
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.
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.
\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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With