2

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 3

2

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)));

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.