Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my parseInt function is not converting my string into integer?

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);
like image 662
maskedjellybean Avatar asked Apr 12 '26 10:04

maskedjellybean


2 Answers

You are doing string concatenation due to order of + - add braces to fix:

 var newImg= imageProject + (imageInt + 1) + ".jpg";
like image 51
Alexei Levenkov Avatar answered Apr 15 '26 00:04

Alexei Levenkov


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

like image 21
HBP Avatar answered Apr 14 '26 22:04

HBP