Files
30-seconds-of-code/snippets/indent-string.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

23 lines
639 B
Markdown

---
title: Indent string
tags: string
cover: clutter
firstSeen: 2018-09-24T22:14:27+03:00
lastUpdated: 2020-11-01T20:50:57+02:00
---
Indents each line in the provided string.
- Use `String.prototype.replace()` and a regular expression to add the character specified by `indent` `count` times at the start of each line.
- Omit the third argument, `indent`, to use a default indentation character of `' '`.
```js
const indentString = (str, count, indent = ' ') =>
str.replace(/^/gm, indent.repeat(count));
```
```js
indentString('Lorem\nIpsum', 2); // ' Lorem\n Ipsum'
indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'
```