Don*_*mmy 1 javascript regex optimization
我想在字符串的开头找到选项卡的数量(当然我希望它是快速运行的代码 ;) )。这是我的想法,但不确定这是否是最好/最快的选择:
//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;
Run Code Online (Sandbox Code Playgroud)
另一种可能性是使用循环和 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++;
Run Code Online (Sandbox Code Playgroud)
在一般的,如果你可以通过简单地通过串迭代和各项指标在做一个字符检查的数据进行计算,这将是比正则表达式更快其中大部分建立更复杂的搜索引擎。我鼓励您对此进行概要分析,但我认为您会发现直接搜索更快。
注意:您的搜索应该使用===而不是==这里,因为您不需要在等式检查中引入转换
function numberOfTabs(text) {
var count = 0;
var index = 0;
while (text.charAt(index++) === "\t") {
count++;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)