user1996496 user1996496 - 3 months ago 10
Javascript Question

How do I extract and split coordinates from jQuery values inside brackets?

I'm getting coordinates via jQuery like this and fill them into a form:

$('#location').val(pos);


The problem is that the value is filled in like this:

(40.00000, 150.00000)


How do I extract them from the brackets and "split" them into latitude & longitude values like:

pos_lat = 40.00000;
pos_long = 150.00000;

Answer

https://jsfiddle.net/ojcoj74y/

var pos = "(40.00000, 150.00000)";
var pos_segs = pos.slice(1,-1).split(', ');
var pos_lat = pos_segs[0];
var pos_long = pos_segs[1];

UPDATE:

Thanks! Is it possible to run this within a function, too? – user1996496 1 hour ago

https://jsfiddle.net/ojcoj74y/1/

function getPos(strPos) {
  var pos_segs = strPos.slice(1, -1).split(', ');

  return {
    posLat: pos_segs[0],
    posLong: pos_segs[1]
  };
}
Comments