3

I want to get the index of First ever character appear in the string.

for example : I have a string " 225 get first character " In this I want the index of 'g' .how to get this ?

thanks

2
  • 1
    Have you ever taken a look at RegExpressions? Commented Oct 21, 2013 at 8:23
  • @reporter ..Can you help me out with this one ? Commented Oct 21, 2013 at 8:26

4 Answers 4

11
var str = " 225 get first character ";
var index = /[a-z]/i.exec(str).index;
alert(index); // 5
Sign up to request clarification or add additional context in comments.

3 Comments

it will return 4..anyways it helped me :)
It returns 5 on latest Firefox.
This is a regex literal case insensitive /i search for English letters, returning a zero based index of the match in string. Very nice!
8

You may use a regular expression:

var str = " 225 get first character ";
var firstChar = str.match('[a-zA-Z]');
//'g'

And if you want the index,

var index = str.indexOf(firstChar);

Comments

1

I have simplified @Jorgeblom answer:

var str = "  255 get first character";
var firstCharIndex = str.match('[a-zA-Z]').index;

console.log(firstCharIndex);
// 6

The match() function return a array with following values:

  • [0] - First matching character => "g"
  • [index] - Index of the first match => 6
  • [input] - the whole input string
  • [groups] - empty in these case. If you declare grouped regex conditions, these groups will be listed here with the matching results

Comments

0

you can use
var str = " 225 get first character ";
var first_char = str.search(/[a-zA-Z]/);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.