Clean up more than two spaces and new lines with regex

Clean up more than two spaces and new lines with regex
Reading Time: < 1 minute

Regular expressions are those I don’t use so frequently so I need to wrap them all in a method with a short explanation about what they do.
So I created a simple JavaScript method that removes all newlines and multiple spaces (including tab spaces) by a single space

/**
 * It replace all new lines and multiple spaces (including tab spaces) by a single space
 * @param {string } text
 * @return {string} a new cleaned string
 */
function cleanUpSpaces(text) {
    if (!text) {
        return text;
    }
    // s{2,} matches any white space (length >= 2) character (equal to [rntfv ])
    return text.replace(/s{2,}/g, ' ');
};

Output example

      
// given
`SELECT *
            FROM account        WHERE id =    1234`

// output
SELECT * FROM account WHERE id = 1234

,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Join 22 other subscribers

Leave a Reply