What am I going wrong here? I'm trying to convert a string to an integer to use in addition.
I have an image with a class of portfolio and a src of images/portfolio-images/gbn1.jpg
The first alert says the value of imageInt is 1, but the second alert says the value of newImg is gbn11.jpg when I'm trying to get gbn2.jpg.
I am posting my code below:
var mainImg = $('.active-more').closest(".container").find("img.portfolio:first").attr("src");
var nofilename = mainImg.replace("images/portfolio-images/","");
nofilename = nofilename.replace(".jpg","");
var imageString = nofilename.replace(/[A-Za-z$-]/g, "");
var imageInt = parseInt(imageString, 10);
var imageProject = nofilename.replace(/\d+/g, '');
alert(imageInt);
var newImg= imageProject + imageInt + 1 + ".jpg";
alert(newImg);
You are doing string concatenation due to order of + - add braces to fix:
var newImg= imageProject + (imageInt + 1) + ".jpg";
Try this :
var newImg= imageProject + (imageInt + 1) + ".jpg";
The + operator is used to add numbers and to concatenate strings. If the left operand is a string then the right one is converted to a string.
In the above, by enclosing the imageInt + 1 in parentheses we ensure that it is evaluated as an integer before being concatenated as a string.
See the fiddle : http://jsfiddle.net/VQG5j
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With