I have the following in a textarea:
link|10000
link|25000
link|58932
I need to remove the characters before the "|"on each line and get the sum of the all the numbers
Any help will be greatly appreciated!
Another solution :
function myFunction() { document.getElementById("demo").innerHTML = document.getElementById("myTextarea").value.split("link|").map(Number).reduce(function(a, b){return a+b; }); }
Calculate:<br> <textarea id="myTextarea"> link|10000 link|25000 link|58932</textarea> <p>Click the button to calculate.</p> <button type="button" onclick="myFunction()">Calculate it</button> <p id="demo"></p>
A short solution:
// Gets textarea content
var myTextareaText = document.getElementById('my-textarea-id').value;
// Uses array functions to simplify the process
let sum = myTextareaText.split('\n').map(x=>x.split('|')[1] * 1).reduce((a,b)=>a+b);
// Logs de result
console.log(sum);
What was done:
1) Break by line breaks : myTextareaText.split('\\n')
2) Foreach line, break by "|", gets the second item and convert it to number: map(x=>x.split('|')[1] * 1)
3) Sum each element: reduce((a,b)=>a+b)
Get all numbers from the value using String#match
method and calculate the sum using Array#reduce
method.
var ele = document.getElementById('text'); // get the text area value var res = ele.value // get all digits combinations , if you want decimal number then use /\\d+(\\.\\d+)?/g .match(/\\d+/g) // iterate and calculate the sum .reduce(function(sum, v) { // parse the number and add it with previous value return sum + Number(v); // set initial value as 0 }, 0); console.log(res);
<textarea id="text">link|10000 link|25000 link|58932 </textarea>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.