简体   繁体   中英

Parse a character out of a string

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?

您可以使用正则表达式从字符串中获取数字:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM