How can I automatically replace all instances of multiple spaces, with a single space, in Javascript?
I've tried chaining some s.replace
but this doesn't seem optimal.
I'm using jQuery as well, in case it's a builtin functionality.
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 JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s . Expand the whitespace selection from a single space to multiple using the \s+ RegEx.
Continuing with that same thought, if your string with spaces is already stored in a variable, you can simply use echo unquoted within command substitution to have bash remove the additional whitespace for your, e.g. $ foo="too many spaces."; bar=$(echo $foo); echo "$bar" too many spaces.
You could use a regular expression replace:
str = str.replace(/ +(?= )/g,'');
Credit: The above regex was taken from Regex to replace multiple spaces with a single space
There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:
str.replace( /\s\s+/g, ' ' )
See this question for a full discussion on this exact problem: Regex to replace multiple spaces with a single space
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