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 : ' ';
})
);