How to replace multiple spaces in a string with a single space between words in TypeScript

1 Answer

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

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

const str: string = "   This   is    a   string   with   multiple    spaces   ";

const outputString: string = replaceMultipleSpaces(str);

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


   
/*
run:
    
"This is a string with multiple spaces"

*/

 



answered Apr 4 by avibootz
...