简体   繁体   中英

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

I have a lot of lines like these:

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>

The answers after should be:

35.04
35.01
32.04

I need to get rid of everything except for the price tag (get rid of everything before and after the price tag) which should be rounded to 2. So far every time I put this in my notepad++ I have to do regex manually in notepad++ like \\bID:\\w+-\\w+-\\w+-\\w+-\\w+\\b and \\d+/\\d+/\\d{4} and \\b\\w+\\b every time I paste it I have to ctrl + h and find which wastes a lot of time. If the program can automatically replace on launch that would be awesome.

I tried to get rid of the decimals with these:

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

First split the text on newline to get an array of lines. With forEach or map you can now split again on space if the price is always the third field and then format it.

 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>

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.

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