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

How to get the Index of First Character from a string contains numeric values using javascript - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

4 Answers 4

Reset to default 11
var 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]/);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论