Replace Multiple Whitespaces with Single Whitespace in JavaScript String

Regex to replace multiple spaces with a single space

Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':

string = string.replace(/\s\s+/g, ' ');

If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

string = string.replace(/  +/g, ' ');

Replace multiple whitespaces with single whitespace in JavaScript string

Something like this:

var s = "  a  b     c  ";
console.log( s.replace(/\s+/g, ' '))

Remove all multiple spaces in Javascript and replace with single space

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

How do I replace multiple spaces with a single space in C#?

string sentence = "This is a sentence with multiple    spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");

replace multiple whitespace with single space but keep new lines in regex match (python)

You can use code below:

import re
test = "This is a test. \n Blah blah."
print(re.sub(r"(?:(?!\n)\s)+", " ",test))

Output

This is a test. 
Blah blah.

Regex to replace multiple spaces to single space excluding leading spaces

You can use a regex like this:

\b\s+\b

With a space _ substitution

Working demo

Sample Image

Update for IntelliJ: seems the lookarounds aren't working on IntelliJ, so you can try this other workaround:

(\w+ )\s+

With replacement string: $1

Working demo

Of course, above regex will narrow the scenarios but you can try with that.

How to replace all spaces in a string

var result = replaceSpace.replace(/ /g, ";");

Here, / /g is a regex (regular expression). The flag g means global. It causes all matches to be replaced.

How to remove duplicate white spaces in a string?

try

"abc                  def. fds                            sdff."
.replace(/\s+/g,' ')

or

"abc                  def. fds                            sdff."
.split(/\s+/)
.join(' ');

or use this allTrim String extension

String.prototype.allTrim = String.prototype.allTrim ||
function(){
return this.replace(/\s+/g,' ')
.replace(/^\s+|\s+$/,'');
};
//usage:
alert(' too much whitespace here right? '.allTrim());
//=> "too much whitespace here right?"


Related Topics



Leave a reply



Submit