- Instant help with your JavaScript coding problems

Remove all extra spaces from a string in JavaScript

Question:
How to remove all extra spaces from a string in JavaScript?
Answer:
const removeExtraSpaces = (text) => {
    if (!text) {
        return '';
    }
    return text.replace(/s+/g, ' ').trim();
}
Description:

A common requirement when normalizing user inputs is to remove all unnecessary whitespace characters from the text. In practice, this means removing all space characters from the beginning and end of the string using the trim method. In addition, the duplicate space characters in the body of the text are replaced with a simple one using the replace method.

To replace multiple space characters in a row with a single one use the replace() method with regexp like this: replace(/s+/g, ' ') . Finally you only need to call trim() to remove all spaces from both ends of a string.

Share "How to remove all extra spaces from a string in JavaScript?"
Related snippets:
Tags:
remove, delete, space, whitespace, string, javascript, all
Technical term:
Remove all extra spaces from a string in JavaScript