Reputation: 95
I want extract lat. and longitude vals from a string like this:
var data = "(-20.210696507479017, -70.14000177383423),(-20.21202551027535, -70.14246940612793),(-20.21385790460967, -70.14066696166992),(-20.21168319245841, -70.13901472091675)"
How can I extract these pairs and push them into a array if these points can change in quantity?
Thanks
Upvotes: 1
Views: 130
Reputation: 21086
Why not transform it into a json string array, then parse it to an object.
var data = "(-20.210696507479017, -70.14000177383423),(-20.21202551027535, -70.14246940612793),(-20.21385790460967, -70.14066696166992),(-20.21168319245841, -70.13901472091675)";
var arr = JSON.parse("[" + data.replace(/[)(]/g, "") + "]");
for(var x=0; x<arr.length-1; x+=2)
console.log("lat " + arr[x] + ", lon " + arr[x+1]);
edit x+=2, good catch Iftah
Upvotes: 0
Reputation: 700342
Split the pairs, then split each pair and parse the values. This produces an array of objects that have a lat
and lng
property that are numbers:
var coors = data.split('),(');
for (var i = 0; i < coors.length; i++) {
var c = coors[i].replace('(', '').replace(')', '').split(',');
coors[i] = { lat: parseFloat(c[0]), lng: parseFloat(c[1]) };
}
Demo: http://jsfiddle.net/Guffa/EV2h4/
Upvotes: 1