Reputation: 1083
I have coordinates in my attribute data-coordinates
<a class="cor" href="#" data-coordinates="37.650621, 55.740887"></a>
I need slice them into two variables, like this
<script>
//this must contain coordinate which is before ","
var firstCor = $('.cor').attr('data-coordinates');
//this must contain coordinate which is after ","
var lastCor = $('.cor').attr('data-coordinates');
</script>
So then, I must have two variable from one data-coordinates
Upvotes: 0
Views: 152
Reputation: 57105
Use .split()
var cor = $('.cor').data('coordinates').split(','); // creates an array of result
var firstCor = cor[0].trim(); // access 1st value index starts from 0
var lastCor = cor[1].trim(); //.trim() to remove empty spaces from start and end
For old browser Support use
var firstCor = $.trim(cor[0]);
var lastCor = $.trim(cor[1]);
or Use String.prototype.trim polyfill
Upvotes: 2
Reputation: 207501
Another way is to use a regular expression
var cords = $('.cor').data('coordinates').match(/-?\d+\.\d+/g);
which results in array with two strings
["37.650621", "55.740887"]
If you want to convert them to numbers and the browser supports Array map()
var cords = $('.cor')
.data('coordinates')
.match(/-?\d+\.\d+/g)
.map( function(a){ return parseFloat(a); });
which results in
[37.650621, 55.740887]
Upvotes: 1
Reputation: 8940
var co = $('.cor').data('coordinates');
var temp=new Array();
temp=co.split(",");
var firstCor =temp[0];
var lastCor = temp[1];
Upvotes: 1