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

后端 未结 2 1677
清歌不尽
清歌不尽 2021-01-23 07:02

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

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-23 07:57

    ^ 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(".");
    });
    	1 leading tab, 1 trailing tab	
    		2 leading tabs, 1 trailing tab	
    			3 leading tabs, 1 trailing tab	
    

提交回复
热议问题