Javascript Regular Expression to replace only multiple occurrences with that substitute

Viewed 43

I am trying to replace multiple spaces with as many ' ' as there are spaces. However, I do not want to replace single spaces.

let string = 'The quick  brown fox   jumped over    a lazy      dog';

My desired output is

"The quick  brown fox   jumped over    a lazy      dog"

I am able to do this by string.replace(/(\S)( )(\S)/g, "$1~$3").replace(/ /g, ' ').replace(/~/g, ' ');. But this requires the string to be scanned through three replace statements. I am replacing single spaces with ~, then all spaces with nbsp; and then finally reverting ~ to single spaces. Is there an easier way of doing this by just one scan?

3 Answers

If you're using a browser that supports lookbehinds, you can use them to replace a space which is either preceded or followed by another space with   using this regex:

(?<= ) | (?= )

Demo on regex101

let string = 'The quick  brown fox   jumped over    a lazy      dog';

console.log(string.replace(/(?<= ) | (?= )/g, '&nbsp;'));

If your browser doesn't support lookbehinds, you can use a callback to replace a sequence of 2 or more spaces with a string of &nbsp; of the same length:

let string = 'The quick  brown fox   jumped over    a lazy      dog';

console.log(string.replace(/ {2,}/g, (m) => '&nbsp;'.repeat(m.length)));

You should be matching on [ ]{2,}, and then replacing the spaces there with &nbsp;. A regex function callback comes in handy here:

var string = 'The quick  brown fox   jumped over    a lazy      dog';
var output = string.replace(/[ ]{2,}/g, function(match, contents, offset, string)
    {
        return match.replace(/[ ]/g, '&nbsp;');
    }
);
console.log(output);

You can use split() and join() together.

let string = 'The quick  brown fox   jumped over    a lazy      dog';
const trimmedString = string.split("  ").join("&nbsp;")
console.log(trimmedString)

Related