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
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
Share Improve this question asked Oct 21, 2013 at 8:22 RajeevRajeev 631 silver badge6 bronze badges 2- 1 Have you ever taken a look at RegExpressions? – Reporter Commented Oct 21, 2013 at 8:23
- @reporter ..Can you help me out with this one ? – Rajeev Commented Oct 21, 2013 at 8:26
4 Answers
Reset to default 11var str = " 225 get first character ";
var index = /[a-z]/i.exec(str).index;
alert(index); // 5
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);
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
you can use
var str = " 225 get first character ";
var first_char = str.search(/[a-zA-Z]/);