如何获取String中第一个数字的索引

Hus*_*sky 15 javascript regex

我需要找出如何获取String中第一个数字的索引.我知道如何使用一些循环,但它会非常难看所以我更喜欢一些正则表达式.有人能告诉我如何使用正则表达式做到这一点?

epa*_*llo 16

搜索: [最快的方式]

var str = "asdf1";
var search = str.search(/\d/)
console.log(search);
Run Code Online (Sandbox Code Playgroud)

匹配: [比for循环慢,只是显示另一种方式]

var str = "asdf1";
var match = str.match(/(\D+)?\d/)
var index = match ? match[0].length-1 : -1;
console.log(index);
Run Code Online (Sandbox Code Playgroud)


Vor*_*ato 10

firstDigit = 'Testi2ng4'.match(/\d/) // will give you the first digit in the string
indexed = 'Test2ing4'.indexOf(firstDigit)
Run Code Online (Sandbox Code Playgroud)

好吧,我想我需要更仔细地看看我的方法,你可以这么做'Testin323g'.search(/\d/);


alo*_*ica 7

for 循环比基于正则表达式的解决方案更快:

function indexOfFirstDigit(input) {
  let i = 0;
  for (; input[i] < '0' || input[i] > '9'; i++);
  return i == input.length ? -1 : i;
}

function indexOfNaN(input) {
  let i = 0;
  for (; input[i] >= '0' && input[i] <= '9'; i++);
  return i == input.length ? -1 : i;
}
Run Code Online (Sandbox Code Playgroud)

在线试试吧!

jsbench(越高越好):

TestCase results for your browser Firefox version 54.0
Test name               Benchmark results
indexOfFirstDigit        11,175,400 (±2.77)
regex search             3,787,617 (±5.22) (epascarello)
regex match              2,157,958 (±6.49) (epascarello)
regex match + indexOf    1,131,094 (±4.63) (VoronoiPotato)
Run Code Online (Sandbox Code Playgroud)

我再次运行了一些快速测试。还是最快的:

比赛图表

自己运行吧!