For more tips like this, sign up to the weekly newsletter!

How to replace characters from the beginning of a String

I needed to replace the leading tabs to two  s in one of my projects. Javascript offers a replace function that seems fit for this task, but unfortunately, it seems there are no trivial solutions.

Using /\t/g matches all the tabs, not just the leading ones:

"\tstr\t".replace(/\t/g, "  ")
// "  str  "

By modifying the expression to only match tabs from the beginning only inserts the replacement text once:

"\t\tstr\t".replace(/^\t+/, "  ")
// "  str\t"
Using a replacer function

Fortunately, replace also accepts a replacer function instead of a replacement text.

The only problem with the /^\t+/ solution is that it matches all the leading tabs. The replacer function then gets a String containing all of them.

So the only thing needed is to replace all characters in that String to the target text.

A trivial solution is to convert the String to a character Array, map all elements and join them together:

"\t\tstr\t".replace(
  /^\t+/,
  (tabs) => tabs.
    split("").
    map(() => "  ").
    join("")
)
// "    str\t"

Note: Instead of tabs.split(""), [...tabs] works as well. This is because a String is an iterable structure and [...tabs] converts it to a full-fledged Array.

Another solution is to use replace again to match and replace all characters:

"\t\tstr\t".replace(
  /^\t+/,
  (tabs) => tabs.
    replace(
      /./g,
      "  "
    )
)
// "    str\t"
Try it
References
Learn more: