Ad

How Retrieve Two Numbers In String Using Regex

- 1 answer

I'm trying to retrieve the two integers (not floating numbers) from the following string:

 0 1 
 0 2 
 0 3 
 0 4 
 0 5 
 0 6 
 0 7 
 0 8 
 12 11
 10 22
 33 2
 102 149

I want to get in javasScript like:

 var line = "0 1";
 var firstInt = line.someMagic();
 var secondInt = line.someMagic();

please help. Any help will be appreciated. thanks!

EDIT

the split method can't be used.
cos sometimes the line has extra space in front or at the end of each line!

like:

var line = " 0 2 ";

that's why I needed the regex.

EDIT 2

Turns out, I don't need the regex!

thanks for the help!

Ad

Answer

Just split the line on the space, and parseInt the chars into numbers :)

var line = "-21 42";

var ints = line.split(' ').map(function (num) {
    return parseInt(num, 10);
});

var firstInt = ints[0]; // -21
var secondInt = ints[1]; // 42

Edit:

If you are worried about trailing spaces etc, just trim the string first:

var ints = line.trim().split(' ').map(...
Ad
source: stackoverflow.com
Ad