0

I have two variable. both have some value like.

var position = "340px";
var end_position = "4px";
var final = position + end_position;
//result comes NAN 
// sometime it return 340px4px
// i want 344px

how do i add these value to get desirable result. Help will be appreciated.

3
  • you need to remove x from string and use parseInt javascript function Commented Mar 18, 2018 at 12:46
  • There's many different ways to do that. Commented Mar 18, 2018 at 12:51
  • Ideally you shouldn't store units along with the position value. It should be a unit-less number. Add unit just before actual usage. Commented Mar 18, 2018 at 15:13

5 Answers 5

2

You could use parseInt

var position = "340px";
var end_posiiton = "4px";
var final = parseInt(position, 10) + parseInt(end_position,10) + "px";
Sign up to request clarification or add additional context in comments.

2 Comments

What is the additional parameter 10 for? Decimal system?
"radix - Optional. A number (from 2 to 36) that represents the numeral system to be used"
1

You can use parseInt (or parseFloat depends on number) and add both numbers

var position = "340px";
var end_position = "4px";
var final = ( parseInt(position) + parseInt(end_position) ) + "px";

console.log( final )

Comments

1

You're concatenating strings rather than adding numbers, to avoid that, you can remove anything different than a number (i.e: using regex) and then execute the add operation. Further, you need to convert the operands as numbers.

To convert the operands as numbers, you can use either the object Number or simply prefix them with +.

Prefixing with +

var position = "340px";
var end_position = "4px";
var final = +position.replace(/[^\d]/g, '') + +end_position.replace(/[^\d]/g, '') + 'px';

console.log(final)

Using the object Number

var position = "340px";
var end_position = "4px";
var final = Number(position.replace(/[^\d]/g, '')) + Number(end_position.replace(/[^\d]/g, '')) + 'px';

console.log(final)

Comments

1

you need to convert the string to int, do the sum the convert them back to strings

    var position = "340px";
    var end_position = "4px";
      var final = (parseInt(position) + parseInt(end_position)).toString()+"px";
console.log(final);
  //result comes NAN 
  // sometime it return 340px4px
  // i want 344px

1 Comment

technically, toString() is superfluous.
0

One more variation to do it using Array.prototype.split:

var position = "340px"
var end_position = "4px"
var final = +position.split('px')[0] + +end_position.split('px')[0] + "px"

console.log(final)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.