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

javascript - Parse a character out of a string - Stack Overflow

programmeradmin6浏览0评论

I have a number of string like this:

var info = "Information4Table"
var next = "Joe5Table"
var four = "ERweer11Table"
var nice = "ertertertn14Table"

I want to parse out the number between the first word and the string Table. So for the first item, I want to get 4 and in the last I would want to get 14. What would be the best way to do this in Javascript/jQuery?

I have a number of string like this:

var info = "Information4Table"
var next = "Joe5Table"
var four = "ERweer11Table"
var nice = "ertertertn14Table"

I want to parse out the number between the first word and the string Table. So for the first item, I want to get 4 and in the last I would want to get 14. What would be the best way to do this in Javascript/jQuery?

Share Improve this question edited Feb 10, 2013 at 5:09 Mechanical snail 30.7k14 gold badges90 silver badges113 bronze badges asked Jan 18, 2010 at 1:12 leoraleora 197k368 gold badges906 silver badges1.4k bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You can use a regular expression to get the number from the string:

var n = /\d+/.exec(info)[0];

Another option would be to use regular expressions to take numbers out of the string:

var my_str="ERweer11Table";
var my_pattern=/\d+/g;
document.write(my_pattern.match(patt1));

This would output "11"

You can use a regular expression for just this sort of thing, especially handy/performant if the pattern doesn't change:

var regex = new RegExp(/[0-9]+/);   // or \d+ will also capture all digits
var matches = +regex.exec(yourStringHere);
var value = matches ? matches[0] : "";

Keep around the regex object and you can use it for all your processing needs. The matches variable will contain null if there's no number in the string, or an array with the matches if there was one or more. The value will have your number in it. The leading '+' operator ensures it's a number type instead of a string type.

发布评论

评论列表(0)

  1. 暂无评论