javascript - Sum text strings on a page -


let's have numbers spread throughout page:

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

luckily, wrapped in curly brackets {}. using javascript — jquery not available —, how add these number return total: 16 in case.

this solution demonstrates getting text page using node.textcontent, matching floating point number (this includes whole integers) exponent (if exists) surrounded in "{" , "}" not consuming trailing "}", using regex, , performing sum of them . during sum remove leading "{" using string slice.

html

<div>lorem ipsum<span>dolor sit amet, </span>{5} consectetur adipisicing<span>elit {2}, sed 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 = 0; var sum = 0;  while (i < length) {     sum += parsefloat(array[i].slice(1));     += 1; }  console.log(sum); 

on jsfiddle

for interest sake, here jsperf of current (3) answers.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -