Alex Rivera | Logout

Replace multiple whitespaces with single whitespace in JavaScript string

Asked 2011-05-28T17:16:57.070
215

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?

Edit
Report

2 Answers

400

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)

answered 2011-05-28T17:18:54.270
4

var x = " Test Test Test ".split(" ").join(""); alert(x);

answered 2012-10-22T05:25:55.810

Your Answer