-
Notifications
You must be signed in to change notification settings - Fork 12.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
16449f1
commit 80ba1db
Showing
1 changed file
with
9 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,23 @@ | ||
--- | ||
title: Expand tabs into spaces | ||
type: snippet | ||
type: tip | ||
language: javascript | ||
tags: [string,regexp] | ||
cover: naming-conventions | ||
excerpt: Convert tabs to spaces, where each tab corresponds to `count` spaces. | ||
excerpt: Convert tabs to spaces, allowing you to control the number of spaces each tab corresponds to. | ||
listed: true | ||
dateModified: 2020-09-15 | ||
dateModified: 2024-08-08 | ||
--- | ||
|
||
Convert tabs to spaces, where each tab corresponds to `count` spaces. | ||
Tabs vs. spaces is a long-standing debate in the programming community. I don't feel like getting into that debate, but I can help you convert tabs to spaces in JavaScript. | ||
|
||
- Use `String.prototype.replace()` with a regular expression and `String.prototype.repeat()` to replace each tab character with `count` spaces. | ||
This entire exercise is a simple matter of **replacing each tab character** with a certain number of spaces. You can **control the number of spaces** each tab corresponds to via the `count` argument, allowing you to customize the output to your liking. | ||
|
||
Simply put, using `String.prototype.replace()` with a **regular expression** and `String.prototype.repeat()` will do the trick. The regular expression `/\t/g` matches all tab characters in the string, which are then replaced with `count` spaces. | ||
|
||
```js | ||
const expandTabs = (str, count) => str.replace(/\t/g, ' '.repeat(count)); | ||
|
||
expandTabs('\t\tlorem', 3); // ' lorem' | ||
expandTabs('\t\tlorem', 3); | ||
// ' lorem' | ||
``` |