簡體   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