Clean up more than two spaces and new lines with regex


Posted on Aug 28, 2020


featured image

Regular expressions are those I don't use so frequent so I need to wrap them all in a method with a short explanation about what them do

So I created simple JavaScript method that removes all new lines 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 [\r\n\t\f\v ])
    return text.replace(/\s{2,}/g, ' ');
};


Example

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

// output
SELECT * FROM account WHERE id = 1234

Photo by Lucas Hobbs on Unsplash

js utils regex dev
Search
Side Widget
You can put anything you want inside of these side widgets. They are easy to use, and feature the new Bootstrap 4 card containers!