skip to Main Content

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


  1. 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’.

    Login or Signup to reply.
  2. Try like this

    var v1 = "45px";
    var v2 = "50px";
    
    var add = parseInt(v1) + parseInt(v2);
    var result = add + "px";
    
    console.log(result);

    parseInt converts to a number and that allows you to do the math.
    See MDN: JavaScript docs – parseInt

    Login or Signup to reply.
  3. 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.

    const s1 = '45px';
    const s2 = '50px';
    const s3 = '10px';
    const s4 = '5px';
    
    // Accept list of pixel strings which you can coerce
    // to an array with rest params
    function addPixelNumbers(...pixelStrings) {
    
      // Create a sum by reducing over the strings,
      // and for each use a regex to extract the digits
      // coerce it to a number, and add it to the accumulator
      const sum = pixelStrings.reduce((acc, c) => {
        return acc + Number(c.match(/d+/));
      }, 0);
    
      // Finally return a new string formed from the sum
      return `${sum}px`;
    }
    
    console.log(addPixelNumbers(s1, s2, s3, s4))

    Additional documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search