Javascript find index of first non alphabetic char from certain position

8.5k views Asked by At

I want to finn the indexOF first non-aplhabetic char from a certain postion on

Example

abc4sss5gggg10

I wan to to get the position of 5 but to specify where I start searching

6

There are 6 answers

0
ozil On
var str = "abc4sss5gggg10";

function searchIndex(index, strng) {
    var arr = strng.split("");
    for (var i = index; i < arr.length; i++) {
        if (!isNaN(arr[i])) {
            return i;
        }
    }
    return -1;
}
alert(searchIndex(4, str));  

DEMO

2
rst On

Consider first this post here Return positions of a regex match() in Javascript?

Then know that to find the first numeric value you have to use

var n = 2; // my starting position
var match = /[0-9]/.exec("abc4sss5gggg10".substring(n));
if (match) {
    alert("match found at " + match.index);
}

Use substring to remove the first n characters

0
Mathijs Segers On

Your first thought might be regex, allthough those are heavy I'd probably go something like

getFirstNonAlpha(str) {
   for (var i = 0; i<str.length;i++) {
      if (!isNaN(str[i]) {
         return i;
      }
   }
   return false;
}

isNaN means isnotanumber so if it matches a number it'll return false and you can return the index.

Check which you need and which has a better speed if this is even an issue. Also this function won't help you with !@#$%^&*()_ etc.

1
Glorfindel On

Use a combination of regular expressions and the substring function:

var str = "abc4sss5gggg10";
var indexToSearchFrom = 6;
var index = str.substring(indexToSearchFrom).search(/[^A-Za-z]/);
0
Avinash Raj On

To get the index of first non-alpha char after the 4th position.

> 'abc4sss5gggg10'.replace(/^.{4}/, "").match(/[^a-z]/i)
[ '5',
  index: 3,
  input: 'sss5gggg10' ]
> 'abc4sss5gggg10'.replace(/^.{4}/, "").match(/[^a-z]/i)['index']
3
0
Hassan Habib On

I think this is what you need:

I modified Mathijs Segers's code so it looks like this:

function StartSearching(str, startFrom) {
   for (var i = startFrom; i<str.length;i++) {
      if (!isNaN(str[i])) {
         return i;
      }
   }
}