ILikeTacos
ILikeTacos

Reputation: 18666

In JavaScript, How to extract latitude and longitude from string

I am extracting a string from a database which needs to be parsed into latitude and longitude separately, The string is defined as a "point", in the following format:

(2.340000000,-4.50000000)

I am trying to remove the parenthesis, and then parsed them with the method split() but I haven't been able to come up with a regular expressions that does the job right:

So far I have tried many alternatives, and

var latlong = "(2.34000000, -4.500000000)"
latlong.replace('/[\(\)]//g','');
var coords = latlong.split(',');
var lat = coords[0];
var long = coords[1];

If I run that, all I got is: NaN, -4.500000

What am I doing wrong? Thanks!

Upvotes: 1

Views: 5464

Answers (4)

antyrat
antyrat

Reputation: 27765

You can try to use match function:

var latlong = "(2.34000000, -4.500000000)"
var coords = latlong.match(/\((-?[0-9\.]+), (-?[0-9\.]+)\)/);

var lat = coords[1];
var long = coords[2];
alert('lat: ' + lat);
alert('long: ' + long);

Upvotes: 0

Sameh Serag
Sameh Serag

Reputation: 746

 var latlong = "(2.34000000, -4.500000000)"
 var coords = latlong.replace(/[\(\) ]/g,'').split(',');

 console.log(coords[0])
 console.log(coords[1])

Upvotes: 0

Joseph
Joseph

Reputation: 119837

Seems to work, but you had an extra slash

var value = '(2.340000000,-4.50000000)';

//you had an extra slash here
//           ''''''''''''''''v
value = value.replace(/[\(\)]/g,'').split(',');

console.log(value[0]);
console.log(value[1]);​

Upvotes: 3

LeonardChallis
LeonardChallis

Reputation: 7783

You can cut out the split and just use the match function with the regex \((\-?\d+\.\d+), (\-?\d+\.\d+)\) which will return the two coordinates. Firebug console output:

>>> "(2.34000000, -4.500000000)".match(/\((\-?\d+\.\d+), (\-?\d+\.\d+)\)/);
["(2.34000000, -4.500000000)", "2.34000000", "-4.500000000"]

Upvotes: 0

Related Questions