简体   繁体   中英

Javascript-Arrays: Get the index of the first item, that begins with a letter

Lets say i have the following array:

['1', '1/2', 'fresh', 'tomatoes']

how can i get the index of the first item, that beginns with a letter, in this case "fresh"?

Please note that it should work with every letter, not just with a specific one.

Thanks.

An alternative is using the function findIndex along with a regex to check the first char.

Assuming every string has at least one char.

 let arr = ['1', '1/2', 'fresh', 'tomatoes'], index = arr.findIndex(s => /[az]/i.test(s[0])); console.log(index); 

Using regex, you can use /[a-zA-z]/ (which matches the first letter in a string) together with search() , for every array item using a for loop, and when search(/[a-zA-Z]/) returns 0, stop and return the current index.

 var arr = ['1', '1/2', 'fresh', 'tomatoes']; for(var i = 0; i < arr.length; i++) { if(arr[i].search(/[a-zA-Z]/) == 0) { console.log(i); break; } } 

Here is another solution, this time using character codes:

 var arr = ['1', '1/2', 'fresh', 'tomatoes']; for(var i = 0; i < arr.length; i++) { var x = arr[i][0].charCodeAt(); if((x >= 65 && x <= 90) || (x >= 97 && x <= 122)) { console.log(i); break; } } 

My suggestion:

function myFunction() {
var i;  
var str = ['1', '1/2', 'fresh', 'tomatoes'];
for(i=0; i<str.length; i++){
  if (str[i].charAt(0) >= 'a' && str[i].charAt(0) <= 'z') {
     console.log(i);
  break;    
    }
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM