Reputation: 51
I get a string from my javascript. These strings look like this: 2x2 3x3 and so on.
Now I would like to get the numbers from these strings. What should I do to get 2 from 2x2 and save that number in a variable?
Upvotes: 2
Views: 199
Reputation: 1039498
You could use a regex:
var foo = '2x32';
var matches = foo.match(/^(\d+)x(\d+)$/);
if (matches.length > 2) {
var a = matches[1]; // = 2
var b = matches[2]; // = 32
}
Upvotes: 3
Reputation: 338406
var str = "2x2";
var numbers = str.split("x"); // ["2","2"]
var first = numbers[0]; // "2"
Or, for short
"2x2".split("x")[0]; // "2"
Upvotes: 2