Files
30-seconds-of-code/snippets/compactWhitespace.md
Isabelle Viktoria Maciohsek 2b6f2b1740 Update snippet descriptions & tags
2020-10-18 23:04:45 +03:00

18 lines
434 B
Markdown

---
title: compactWhitespace
tags: string,regexp,beginner
---
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.
```js
const compactWhitespace = str => str.replace(/\s{2,}/g, ' ');
```
```js
compactWhitespace('Lorem Ipsum'); // 'Lorem Ipsum'
compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum'
```