From 60d2238718dffd243920f2276da7896cfb67ce8d Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 1 Jun 2020 17:05:39 +0300 Subject: [PATCH] Add expandTabs --- snippets/expandTabs.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 snippets/expandTabs.md diff --git a/snippets/expandTabs.md b/snippets/expandTabs.md new file mode 100644 index 000000000..279c678b1 --- /dev/null +++ b/snippets/expandTabs.md @@ -0,0 +1,16 @@ +--- +title: expandTabs +tags: string,regexp,beginner +--- + +Convert tabs to spaces, where each tab corresponds to `count` spaces. + +Use `String.prototype.replace()` with a regular expression and `String.prototype.repeat()` to replace each tab character with `count` spaces. + +```js +const expandTabs = (str, count) => str.replace(/\t/g, ' '.repeat(count)); +``` + +```js +expandTabs('\t\tlorem', 3); // ' lorem' +```