【发布时间】:2022-02-15 03:57:19
【问题描述】:
我想在字符串的开头找到制表符的数量(当然我希望它是快速运行的代码;))。这是我的想法,但不确定这是否是最佳/最快的选择:
//The regular expression
var findBegTabs = /(^\t+)/g;
//This string has 3 tabs and 2 spaces: "<tab><tab><space>something<space><tab>"
var str = " something ";
//Look for the tabs at the beginning
var match = reg.exec( str );
//We found...
var numOfTabs = ( match ) ? match[ 0 ].length : 0;
另一种可能是使用循环和charAt:
//This string has 3 tabs and 2 spaces: "<tab><tab><space>something<space><tab>"
var str = " something ";
var numOfTabs = 0;
var start = 0;
//Loop and count number of tabs at beg
while ( str.charAt( start++ ) == "\t" ) numOfTabs++;
【问题讨论】:
-
您在第一个示例中使用了不同的变量名,并且
) )出现了拼写错误。 -
不好意思,我只是写在stackoverflow的textarea里。我会解决的。
-
另外,现在,在 ES6 中,您可以使用如下正则表达式:
'\t\tabc'.match(/\t/gy) || '').length
标签: javascript regex optimization