将行首的所有制表符匹配并替换为四个空格 [英] Match and replace all tabs at the beginning of the line with four spaces

查看:128
本文介绍了将行首的所有制表符匹配并替换为四个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上还阅读了其他一些问题和答案,但是所有这些问题和答案都与我要查找的内容略有不同:用四个空格替换字符串开头的所有制表符.

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'

使用/\t/g查找选项卡并不困难,但这将获得不在行首的选项卡.因此,使用m.match(/(\t\W)/)可以解决上面的示例,导致2个匹配项.

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.

但是使用m.replace(/(\t\W)/, ' ')时,预期结果将是:

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

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

但是我却得到了:

    something // 4 spaces for two tabs.

为什么这一次只能替换两个标签?以及如何用所需的字符串替换每次出现的\t?

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

推荐答案

首先,您要同时替换两个制表符和一个非单词字符,这些字符不一定是制表符,必须用四个空格代替.您没有分别匹配每个\t字符.

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

您可以使用 y标志:

You could use y flag:

console.log(
  "\t\tHello, world!".replace(/\t/gy, '    ')
);

或不使用y修饰符(以支持古老的浏览器),则可以使用一些代码:

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

这篇关于将行首的所有制表符匹配并替换为四个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆