问题
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!
回答1:
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]);
回答2:
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"]
回答3:
You can try to use math 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);
回答4:
var latlong = "(2.34000000, -4.500000000)"
var coords = latlong.replace(/[\(\) ]/g,'').split(',');
console.log(coords[0])
console.log(coords[1])
来源:https://stackoverflow.com/questions/10530279/in-javascript-how-to-extract-latitude-and-longitude-from-string