繁体   English   中英

如何摆脱文本区域/段落中的小数并在开始时启动正则表达式?

[英]How to get rid of decimals in a text-area/paragraph and launch regex at start?

我有很多这样的行:

HTML:

<textarea id="mytext" style="width:500px;height:500px;">
2/9/2020 Apple $35.042 ID:2e35-s2s2-2d29-202s
1/4/2020 Banana $35.012 ID:2e45-d142-24sd-2d2s
1/17/2020 Orange $32.042 ID:2e75-s5s6-2f49-2s1s
</textarea>

<textarea id="myresults" style="width:500px;height:500px;">
</textarea>

后面的答案应该是:

35.04
35.01
32.04

我需要去掉除了价格标签(去掉价格标签前后的所有东西)之外的所有东西,它应该四舍五入为 2。到目前为止,每次我把它放在我的记事本 ++ 中时,我都必须在记事本 ++ 中手动执行正则表达式,例如\\bID:\\w+-\\w+-\\w+-\\w+-\\w+\\b 和 \\d+/\\d+/\\d{4} 和 \\b\\w+\\b 每次粘贴时我都必须 ctrl + h 和找到哪个浪费了很多时间。 如果程序可以在启动时自动替换,那就太棒了。

我试图用这些去掉小数:

<script>
var text = "document.getElementById('mytext');
text.value.toFixed(2); or 
text.toFixed(2); or
text.MathRound(2); or
mytext.toFixed(2); etc
</script>

首先在换行符上拆分文本以获取行数组。 使用 forEach 或 map,如果价格始终是第三个字段,您现在可以在空间上再次拆分,然后对其进行格式化。

 let lines = document.getElementById('mytext').value.split('\\n') let prices = [] lines = lines.filter(function (el) { if (el) { let price = el.match(/\\$\\d+(\\.\\d+)?/g)[0] prices.push('$' + parseFloat(price.substring(1, price.length)).toFixed(2)) }; }) let myresults = document.getElementById("myresults"); myresults.value = prices.join("\\n")
 <textarea id="mytext" style="width:500px;height:500px;"> 2/9/2020 Apple $35.042 ID:2e35-s2s2-2d29-202s 1/4/2020 Banana $35.012 ID:2e45-d142-24sd-2d2s 1/17/2020 Orange $32.042 ID:2e75-s5s6-2f49-2s1s </textarea> <textarea id="myresults" style="width:500px;height:500px;"> </textarea>

暂无
暂无

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

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