Vince Lowe
Vince Lowe

Reputation: 3620

How to parse number from middle of string

I need to parse some numbers from a string, I can get the last number easily but wonder how to get the number mid string reliably. In this case the number 12?

var mystring = 'group 999999999 group-session-info 12 of 50';
var i;
var num; //how to get num "12"
var numOf;
i= mystring.lastIndexOf(" ");
if (i != -1) {
   numOf= mystring.substr(i);
}
alert(numOf); // = 50

Thanks

Upvotes: 2

Views: 2867

Answers (5)

BotMaster
BotMaster

Reputation: 2223

Just to show the correct way but in correct AS3 code and not Javascript for reference:

var mystring:String = 'group 999999999 group-session-info 12 of 50';
var reg:RegExp =  /\d+/g;
var numbers:Array = mystring.match(reg);
trace(Number(numbers[0]))
trace(Number(numbers[1]))
trace(Number(numbers[2]))

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074268

You'll need to know the context, or know how many numbers there are to find.

With context (for instance, 12 has of after it):

var match = mystring.match(/(\d+) of/);
var num = match && match[1];

num will be the string "12" or null if no number followed by "of" was found.

With knowing how many there are, you just grab all the numbers in the string:

var nums = mystring.match(/\d+/g);

Now nums is an array with the strings "999999999", "12", and "99" in it. (Thanks to epascarello for reminding me that match returns an array with his excellent answer.)

Upvotes: 4

Raf Geekee
Raf Geekee

Reputation: 84

If the items are always in the format supplied. I would split using the space character.

var mystring = 'group 999999999 group-session-info 12 of 50';
var num = parseInt(mystring.split(' ')[3]); // 4th item which is 12

Upvotes: 4

epascarello
epascarello

Reputation: 207501

Simple with a regular expression and use map to convert the array of strings to numbers.

var mystring = 'group 999999999 group-session-info 12 of 50';
var nums = mystring.match(/\d+/g).map(Number);

Upvotes: 1

Yu Wu
Yu Wu

Reputation: 213

Try using regular expression to extract all numbers from the string

var mystring = 'group 999999999 group-session-info 12 of 50';
var r = /\d+/g;
mystring.match(r)

The last sentence will result in an array: [ '999999999', '12', '50' ]

But currently each element in the array is a string. Using parseInt() can turn them into numbers.

Hope this helps.

Upvotes: 8

Related Questions