Replace multiple whitespaces with single whitespace in JavaScript string

eve  picture eve · May 28, 2011 · Viewed 190.8k times · Source

I have strings with extra whitespaces, each time there's more than only one whitespace I'd like it be only one.

Anyone? I tried searching google, but nothing worked for me.

Thanks

Answer

bjornd picture bjornd · May 28, 2011

Something like this:

var s = "  a  b     c  ";

console.log(
  s.replace(/\s+/g, ' ')
)