Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove suffixes from numbers

I'm looking for a way to remove suffixes "m", "k", "b", or "%" from numbers in Javascript.

I've successfully matched all digits which are followed by the letters I care about:

\b[\d\.]+[mkb%]\b

Regular expression visualization

Debuggex Demo

Given this set:

10.0 20.0k 30k 40k40 50m 60m6 m 70 m 80b80b 90%

I'd like to remove the suffixes from the 20, 30, 50, 90, and the trailing one from the 80. (the others don't have a word boundary after them)

I'm not clear on how to capture (and then remove) only the suffix portion of this. Little help?

like image 925
SimplGy Avatar asked Aug 24 '26 09:08

SimplGy


2 Answers

Use \b at front and also capture only the digit part. So that the captured chars would be back-referenced in the replacement part.

string.replace(/\b([\d\.]+)[mkb]\b/g, "$1")

DEMO

like image 61
Avinash Raj Avatar answered Aug 26 '26 00:08

Avinash Raj


Put the capture group around just the numeric part, not the whole thing.

/([\d.]+)[mkb]\b/
like image 21
Barmar Avatar answered Aug 25 '26 23:08

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!