How can I remove all the white space from a given string.
Say:
var str = " abc de fog ";
str.trim();
Gives abc de fog
AND NOT abcdefog
, which I want.
How can I get all the white space removed using JavaScript?
Using Split() with Join() method To remove all whitespace characters from the string, use \s instead. That's all about removing all whitespace from a string in JavaScript.
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.
Using regexes with "\s" and doing simple string. split()'s will also remove other whitespace - like newlines, carriage returns, tabs.
The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
Use this:
str.replace(/\s+/g, '');
Instead of this:
str.trim()
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