javascriptstringtrim

Replace multiple whitespaces with single whitespace in JavaScript string


I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?


Solution

  • Something like this:

    const str = "  a  b     c  "
    const result = str.replace(/\s+/g, ' ').trim()
    
    console.log('result', result)
    console.log('result.length', result.length)