Erik Erik - 2 months ago 8
Javascript Question

How to parse two space-delimited numbers with thousand separator?

I need to parse string that contains two numbers that may be in three cases :

"646.60 25.10" => [646.60 25.10]


"1 395.86 13.50" => [1395.86, 13.50]


"13.50 1 783.69" => [13.50, 1 783.69]


In a simple case it's enough use
'number'.join(' ')
but in the some cases there is thousand separator like in second and third ones.

So how could I parse there numbers for all cases?

EDIT: All numbers have a decimal separator in the last segment of a number.

Answer

var string1 = "646.60 25.10";// => [646.60 25.10]

var string2 = "1 395.86 13,50";// => [1395.86, 13,50]

var string3 = "13.50 1 783.69"; // => [13.50, 1 783.69]


function getArray(s) {
var index = s.indexOf(" ", s.indexOf("."));
	return [s.substring(0,index), s.substring(index+1) ];
}


console.log(getArray(string1));
console.log(getArray(string2));
console.log(getArray(string3));

Comments