Match and replace all tabs at the beginning of the line with four spaces

时间:2018-03-25 19:55:45

标签: javascript regex replace match

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 spaces.

What I've tried so far:

let m = '\t\tsomething\t'

Finding tabs isn't hard with /\t/g, but this would get tabs that are not at the beginning of a line. So using m.match(/(\t\W)/) does the trick for the sample above, resulting in 2 matches.

But when using m.replace(/(\t\W)/, ' '), the expected result would be:

        something // 8 spaces (4 for each \t)

but I get this instead:

    something // 4 spaces for two tabs.

Why is this replacing both tabs just one time? And how can I replace every occurrence of \t with the desired string?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

^ 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>