How to replace multiple spaces in a string with a single space between words in Node.js

1 Answer

0 votes
function replaceMultipleSpaces(string) {
    // Use a regular expression to replace multiple spaces with a single space
    let result = string.replace(/\s+/g, ' ');

    // Trim leading and trailing spaces
    return result.trim();
}

const string = "   This   is    a   string   with   multiple    spaces between  words   ";
const outputString = replaceMultipleSpaces(string);

console.log(`"${outputString}"`);



/*
run:

"This is a string with multiple spaces between words"

*/

 



answered Apr 4 by avibootz
...