Files
30-seconds-of-code/snippets/js/s/compact-whitespace.md
2023-05-07 16:07:29 +03:00

524 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Compact whitespaces snippet javascript
string
regexp
travel-mug-1 2020-10-18T23:04:45+03:00

Compacts whitespaces in a string.

  • 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, ' ');
compactWhitespace('Lorem    Ipsum'); // 'Lorem Ipsum'
compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum'