Files
30-seconds-of-code/snippets/indentString.md
Isabelle Viktoria Maciohsek c3a2e47672 Add prototype to descriptions
2020-10-20 11:21:07 +03:00

19 lines
555 B
Markdown

---
title: indentString
tags: string,beginner
---
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 parameter, `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'
```