-1

Hello I have a function that returns numbers inside a <p> tag with the following format:

<p class="numbers">123 + 456 + 789</p>

Is there any way I can do another function or something in javascript to sum up all the numbers and store it into a variable?

Thanks!

Andy
  • 61,948
  • 13
  • 68
  • 95
cup_of
  • 6,397
  • 9
  • 47
  • 94

4 Answers4

3
// Grab the element
const para = document.querySelector('.numbers');

// Convert the text content to an array and
// make the text number values into actual numbers
const numbers = para.textContent.split(' + ').map(Number);

// Use `reduce` to sum the numbers
const total = numbers.reduce((p, c) => p + c);

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
1

This should do it:

var string = "<p class="numbers">123 + 456 + 789</p>";
var numbers = string.split(">")[1].split("<")[0].split("+");
var i = 0;
var sum = 0;
while(i < numbers.length){
    sum += parseInt(numbers[i]);
    i += 1;
}
return sum;
Oliver Browne
  • 51
  • 1
  • 4
  • 1
    One thing to be careful of -- this assumes the numbers are integers. Maybe that's a safe assumption or maybe not, but it will give the wrong answer if you have values like 123.5. – Mark Jul 24 '17 at 04:05
  • Yeah, that's true, but if not you can just swap in "parseFloat", so it shouldn't be a huge problem – Oliver Browne Jul 24 '17 at 04:09
  • If you're going to use `parseInt` you should include the radix for completeness: `parseInt(numbers[i], 10)`. – Andy Jul 24 '17 at 04:15
  • If you don't need to support older browsers (like IE 11) Number() is a nice alternative to parseInt/parseFloat. – Mark Jul 24 '17 at 04:21
1

You can use Array.prototype.reduce()

var n = document.querySelector(".numbers").textContent;

var nums = n.replace(/\s/g, "").match(/^\d+|[+-]\d+/g);

var res = nums.reduce((a, b) => Number(a) + Number(b));

document.body.innerHTML += `=${res}`;
<p class="numbers">123 + 456 + 789</p>
guest271314
  • 1
  • 15
  • 104
  • 177
  • thank you for your answer I gave you an upvote but Ive already selected andys answer. thanks again – cup_of Jul 24 '17 at 04:10
0

var x = document.querySelector('.numbers').textContent.split("+").map(Number);

var y = x.reduce(function(add,num){return add+num})

console.log(y);

Karan Dhir
  • 731
  • 1
  • 6
  • 24