How to remove the extra spaces in a string? How to remove the extra spaces in a string? javascript javascript

How to remove the extra spaces in a string?


You're close.

Remember that replace replaces the found text with the second argument. So:

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

Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!

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


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


Try this one, this will replace 2 or 2+ white spaces from string.

const string = " this contains   spaces ";    string.replace(/\s{2,}/g, '').trim()