Hovhannes Sargsyan
Hovhannes Sargsyan

Reputation: 1083

slice string into two variables

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

Answers (4)

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

.data()

.trim()


Update

For old browser Support use

$.trim() instead of .trim()

var firstCor = $.trim(cor[0]);
var lastCor = $.trim(cor[1]);

or Use String.prototype.trim polyfill

Upvotes: 2

epascarello
epascarello

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

AtanuCSE
AtanuCSE

Reputation: 8940

var co = $('.cor').data('coordinates');

var temp=new Array();

temp=co.split(",");

var firstCor =temp[0];

var lastCor = temp[1];

Upvotes: 1

Satpal
Satpal

Reputation: 133403

Use .split(), if you want to convert in float use parseFloat

 var arr = $('.cor').data('coordinates').split(',');
 var firstCor = $.trim(arr[0]);
 var lastCor  = $.trim(arr[1]);

Upvotes: 1

Related Questions