如何从字符串中提取lat和long值?

时间:2017-05-31 17:18:46

标签: javascript

例如,

'POINT (-109.42948819496439 44.5177967942721)'

如何从前面的字符串中提取lat和long值?

我试过了:

coords.substring(7,14) + ' ' + coords.substring(15,22)

但我认为我不能依赖它

3 个答案:

答案 0 :(得分:6)

// Robust matching of two space-separated floats within parentheses:
let point = 'POINT (-109.42948819496439 44.5177967942721)';
let [, lat, long] = point.match(/\(([+-]?[0-9.]+) ([+-]?[0-9.]+)\)/);

console.log(lat, long);

注意:RegExp仅与提供的测试用例保证一样健壮。如果模式不匹配,则抛出TypeError

答案 1 :(得分:2)

如果格式始终相同,则可以使用substring()

执行此操作



var x = 'POINT (-109.42948819496439 44.5177967942721)';

var lat = x.substring(x.indexOf('(') + 1, x.lastIndexOf(' '));
var lon = x.substring(x.lastIndexOf(' ') + 1, x.indexOf(')'));

console.log(lat);
console.log(lon);




但是,操纵字符串中模式的最佳选择是正则表达式

答案 2 :(得分:1)

var input = 'POINT (-109.42948819496439 44.5177967942721)';
var res = input.replace("POINT ", "");
var res1 = res.replace(")", "");
var res2 = res1.replace("(", "");
var fields = res2.split(' ');

var lat = fields[0];
var long = fields[1];