DEV Community

Cover image for 1 line of code: How to convert tabs to spaces
Martin Krause
Martin Krause

Posted on

11

1 line of code: How to convert tabs to spaces

const tabsToSpaces = (str, tabsize = 4) => str.replaceAll("\t", " ".repeat(tabsize));
Enter fullscreen mode Exit fullscreen mode

Returns the string and replaces a series of spaces (tab size) with a tab.


The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Subscribe to the weekly modern frontend development newsletter


Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (9)

Collapse
 
lexlohr profile image
Alex Lohr

There's an edge case inherent to tabs this one-liner misses: tabs mask previous spaces within their length, so \s\t should become \t, unless tab length was one.

However, if there are no stray spaces hidden beneath the tabs, it should work.

Collapse
 
martinkr profile image
Martin Krause

Hey Alex,

Thank you, good catch! You want to contribute an optimised version and I update the article?

Cheers!

Collapse
 
lexlohr profile image
Alex Lohr • Edited

Unfortunately, that's not a one-liner anymore, as you would have to calculate the expected position of the tab even inside the string, so it's a lot more complex. I would advise to merely document this edge case.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Tabs > Spaces

Collapse
 
martinkr profile image
Martin Krause

:D

Collapse
 
martinkr profile image
Martin Krause
Collapse
 
koas profile image
Koas
Collapse
 
veerasrivastava profile image
Veera Srivastava

cute

Collapse
 
devfranpr profile image
DevFranPR • Edited

Part 1: Get this snippet.
Part 2: Use it on your friend who loves tabs over spaces codebase.
Part 3: Enjoy.

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay