I want to save two different vales as two variables from an image counter class like:
<div class="counter">33 / 111</div>
33 is the number of current image.
111 are the images in total.
I can get the first value with parseInt and save it in a variable.
$(document).ready(function(){
var sc=$('.counter').text();
sc=parseInt(sc);
alert(sc);
});
But how can I get the last number (the total number of images = "111") and put it in another second variable?
var x=$('.counter').text();
x=???parseInt(x)+???;//get the last Number (111)
alert(x); //x=111
First of all, don't use parseInt()
to get the first value. Use split()
to get the values into an array, and then you can grab them from the array, like so:
var values = $('.counter').text().split('/');
And then to get them into separate variables, you can simply reference the relevant index of the array:
var firstValue = values[0];
var secondValue = values[1];
The above solution will return the string values from the div, so if you actually need them as integers, you can convert them separately with parseInt()
like so:
var firstValue = parseInt(values[0]);
var secondValue = parseInt(values[1]);
Or you can convert the entire array to integers before you assign your firstValue
and secondValue
variables, and not have to use parseInt()
in your declarations, like so:
var values = $('.counter').text().split('/').map(Number);
If you're using the new ES6 specification for JavaScript (which has a ton of goodies in it), you can actually do this as a pretty slick one-liner, like so:
let [firstValue, secondValue] = $('.counter').text().split('/').map(Number);