How to get index of the first digit in String

I need to find out how to get the index of the first digit in String. I have an idea how to do that using some loops but it would be really ugly so I would prefer some regex. Could someone give me a clue how to do that using regex?

firstDigit="Testi2ng4".match(/\d/) // will give you the first digit in the string
indexed = 'Test2ing4'.indexOf(firstDigit)

Well I guess I need to look at my methods more closely, you can just do 'Testin323g'.search(/\d/);

Search: [Fastest way]

var str = "asdf1";
var search = str.search(/\d/)
console.log(search);

Match: [Slower than a for loop, just showing another way of doing it]

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

A for loop is fastest than a regex based solution:

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;
}

Try it online!

jsbench (higher is better):

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)

I ran again some quick tests. Still fastest:

chart of the race

Run it yourself!

Use string.search to find the index with the regex \d

If you were just looking for a one liner you could also try a functional programming approach and could do something like the following:

let myStr = "ID12345";
let myStrIndex = myStr.indexOf(myStr.split('').filter(x => !isNaN(parseInt(x, 10)))[0]);

The string is split into an array of characters and the filter function reduces that array to just the number characters. The first character of the new array is the first number character in the string so using indexOf on that character gives you the index you are looking for.

Read More:   How to return values from async functions using async-await from function? [duplicate]

Of course if there is no number character in the string you will get an index of -1 as a result. And you could also use a different check if char is number function as the parameter to .filter() – I am sure there is something faster if that’s a concern


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts