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

后端 未结 2 1678
清歌不尽
清歌不尽 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:33

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

提交回复
热议问题