简体   繁体   English

使用Javascript从Textarea中的每个换行符添加数字

[英]Add Numbers from Each Line Break in Textarea with Javascript

I have the following in a textarea:我在 textarea 中有以下内容:

link|10000链接|10000
link|25000链接|25000
link|58932链接|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') 1) 换行:myTextareaText.split('\\n')
2) Foreach line, break by "|", gets the second item and convert it to number: map(x=>x.split('|')[1] * 1) 2)foreach行,以“|”分隔,得到第二项并转换为数字:map(x=>x.split('|')[1] * 1)
3) Sum each element: reduce((a,b)=>a+b) 3) 对每个元素求和:reduce((a,b)=>a+b)

Get all numbers from the value using String#match method and calculate the sum using Array#reduce method.使用String#match方法从值中获取所有数字,并使用Array#reduce方法计算总和。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM