SimplGy
SimplGy

Reputation: 20437

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?

Upvotes: 3

Views: 250

Answers (2)

Barmar
Barmar

Reputation: 781058

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

/([\d.]+)[mkb]\b/

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174706

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

Upvotes: 4

Related Questions