最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - Javascript find index of first non alphabetic char from certain position - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Jun 16, 2015 at 6:35 foxfox 3875 silver badges16 bronze badges 5
  • 4 first non-alpha char it 4. – Avinash Raj Commented Jun 16, 2015 at 6:36
  • @AvinashRaj char from a certain postion on – Tushar Commented Jun 16, 2015 at 6:38
  • possible duplicate of Return positions of a regex match() in Javascript? – rst Commented Jun 16, 2015 at 6:43
  • You should really show us what you have tried. – Xotic750 Commented Jun 16, 2015 at 8:52
  • Another very similar question with solutions. stackoverflow./questions/273789/… – Xotic750 Commented Aug 26, 2015 at 11:18
Add a ment  | 

6 Answers 6

Reset to default 6

Use a bination of regular expressions and the substring function:

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

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

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

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

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.

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

发布评论

评论列表(0)

  1. 暂无评论