1

Let's say I have a numbers spread throughout a page:

Lorem ipsum dolor sit amet, {5} consectetur adipisicing elit {2}, 
sed do eiusmod {9} tempor incididunt ut labore et dolore magna aliqua. 

Luckily, they are wrapped in curly brackets {}. Using javascript — jQuery is not available —, how do I add these number to return the total: 16 in this case.

1
  • 3
    Use a regex to find the numbers, then loop through the matches and add them up! Commented May 3, 2013 at 1:04

3 Answers 3

3

You can use eval here...

var str = 'Lorem , {5}  elit {2}, sed {9} tempor';

var sum = eval(str.match(/\d+(?=\})/g).join('+'));

/*  returned value: (Number)
16
*/
Sign up to request clarification or add additional context in comments.

4 Comments

While eval is generally a bad idea, this is a reasonable use of it, especially since the input has gone through sanitisation by only allowing digits.
While I agree with Kolink, I don't see why you wouldn't just loop over the matches and add them...instead of joining them with + and evaling it
@Ian- It wouldn't matter unless there are a lot of numbers, but it avoids having to convert the strings to numbers individually.
This will fail if you have a number with a trailing "}" but no leading "{" in the text, I don't know how possible that is in the OPs scenario: jsfiddle.net/Xotic750/aP5Sz
2

Try this:

var str = 'Lorem ipsum dolor sit amet, {5} consectetur adipisicing elit {2}, sed do eiusmod {9} tempor incididunt ut labore et dolore magna aliqua.';

var result = str.match(/\{[^}]+\}/g).join('').match(/\d+/g).reduce(function(a,b) {
  return +a + +b;
});

console.log(result); //=>16

Edit: Check the gmatch helper if you want to make it a bit clearer: http://jsbin.com/asufek/1/edit

5 Comments

Array.prototype.reduce is not avaiable in older browsers.
And there's no reason to run 2 regexes, when it can be done with 1.
@Ian: match doesn't capture groups with g flag that's why the two regex.
My point is that there's no need for 2. kennebec's answer has the regex /\d+(?=\})/g which works fine.
I think there is a need for two if done in this manner, kennebecs answer fails if there is a trailing "}" but no leading "{" around the number
1

This is a solution that demonstrates getting the text from the page using Node.textContent, matching a floating point number (this includes whole integers) with exponent (if exists) surrounded in "{" and "}" but not consuming the trailing "}", using a regex, and then performing a sum of them . During the sum we remove the leading "{" by using String slice.

HTML

<div>Lorem ipsum<span>dolor sit amet, </span>{5} consectetur adipisicing<span>elit {2}, sed do eiusmod</span><span>{9} tempor incididunt ut labore </span>et dolore magna aliqua.</div>

Javascript

var array = document.body.textContent.match(/{[-+]?\d*\.?\d+([eE][-+]?\d+)?(?=\})/g);
var length = array.length;
var i = 0;
var sum = 0;

while (i < length) {
    sum += parseFloat(array[i].slice(1));
    i += 1;
}

console.log(sum);

On jsfiddle

For interest sake, here is a jsperf of the current (3) answers.

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.