How can I perform addition or subtraction on number with text in jQuery?
I have some values with text. I want to use jQuery to add these values .
Here us the values which i want to add :-
45px + 50px and want result 95px
How can I perform addition or subtraction on number with text in jQuery?
I have some values with text. I want to use jQuery to add these values .
Here us the values which i want to add :-
45px + 50px and want result 95px
3
Answers
This is a not way to do but for your knowledge, Try to use parseFloat(’45px’) + parseFloat(’50px’) after you getting result in INT then you need to append ‘px’ with that calculate value. as exmaple 95 + ‘px’.
Try like this
parseInt
converts to a number and that allows you to do the math.See MDN: JavaScript docs – parseInt
You need a JavaScript function that can take a series of pixel strings (like
95px
), add them together, and return a new string.Here a series of arguments is coerced to an array (rest parameters). Using
reduce
to iterate over that array we take each string, grab the number using a regular expression, and add it to the reducer’s accumulator (which starts at zero).Finally a new string is returned using that summed number.
Additional documentation
reduce