const tabsToSpaces = (str, tabsize = 4) => str.replaceAll("\t", " ".repeat(tabsize));
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
Top comments (9)
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.
Hey Alex,
Thank you, good catch! You want to contribute an optimised version and I update the article?
Cheers!
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.
:D
The other way around: 1 line of code: How to convert spaces to tabs
youtu.be/SsoOG6ZeyUI
cute
Part 1: Get this snippet.
Part 2: Use it on your friend who loves tabs over spaces codebase.
Part 3: Enjoy.