'Find index of numbers from a string in Javascript

I would like to get the index of numbers ( 1994 and 27 ) in the string bellow

i tried to split the string but no idea what to do after that

let str = 'year of birth : 1994 , and i'm 27 yo'



Solution 1:[1]

After you split the string. Just loop and check if the value is a number or not.

let str = "year of birth : 1994 , and i'm 27 yo";
strArray = str.split(' ');
    for(let i=0;i<strArray.length;i++){
        //Use isNaN() to check if the value is a number.
        if(isNaN(strArray[i])==false){
            console.log("Number "+strArray[i]+" is at index "+i);
        }
    }

Solution 2:[2]

Simple way to find index

function findindex(str) {
        var num = /\d/;
        var nums = str.match(num);
        return str.indexOf(nums);
    }

console.log(findindex('year of birth : 1994'));//will be 16

Solution 3:[3]

A convenient fast way is to try search().

The syntax is:

str.search(regex);

where (str) is the string to search in. (regex) is the thing you are searching for.

The return value: is the index of the first occurrence of the thing you are after, in your case, a number. From here, it's up to you what to do with this index; i.e.: slicing your string starting at this index, maybe??

An important key to use this method is to have enough understanding of the regex industry, which is out of the scope of your question.

Your example:

let str = "year of birth : 1994 , and i'm 27 yo";
let reg = /\d/;
let ind = str.search(reg);
alert('the first instance of "'+reg+'" is found at index: ' + ind);
// expected result is 16, as it is the index of the number (1) in 1994;

//if you want a certain number (not just any number), you
//can modify the reg variable. Let's search for 94, for example..
reg = /94/;
ind = str.search(reg);
alert('the first instance of "'+reg+'" is found at index: ' + ind);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leo Kamwathi
Solution 2 Snowcat
Solution 3 Ayham Kamel