30 seconds of code

  Back to Home

compactWhitespace

stringregexpbeginner

Returns a string with whitespaces compacted.

Use String.prototype.replace() with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.

const compactWhitespace = str => str.replace(/\s{2,}/g, ' ');