I\'ve read some other questions and answers on the site, but all of them were a little different from what I\'m seeking: replace all tabs at the beginning of a string with four
First off, you are replacing both tabs and a non-word character which may not be a tab character necessarily with four spaces. You are not matching each \t
character separately.
replace all tabs at the beginning of a string with four spaces
You could use y flag:
console.log(
"\t\tHello, world!".replace(/\t/gy, ' ')
);
or without using y
modifier (to support ancient browsers) you could go with a little more bit of code:
console.log(
"\t\tHello, world!\t".replace(/\t|(.+)/gs, function(match, p1) {
return p1 ? p1 : ' ';
})
);
^
means "beginning of line", +
means "one or more times", m
means "multiline" and g
means "greedy" (find all occurrences). Finally, there is a little trick to convert one occurrence of n tabs into n dots (I use dots to prove that I don't replace trailing tabs) :
YYY = "YYY";
n = YYY.length;
(new Array(n + 1)).join("X") // "XXX"
var tabs = document.getElementById("tabs");
var dots = document.getElementById("dots");
var text = tabs.textContent;
dots.textContent = text.replace(/^\t+/mg, function ($0) {
return (new Array($0.length + 1)).join(".");
});
<pre id="tabs">
1 leading tab, 1 trailing tab
2 leading tabs, 1 trailing tab
3 leading tabs, 1 trailing tab
</pre>
<pre id="dots"></pre>