0

I've a chart which in the Y axis I have some numbers, like 40000000, 7000000, 20000000.

I'd like to use a Regex to replace the last six '0' numbers by 'M'

Example

40000000 should be 40M
7000000  should be 7M
20000000 should be 20M

If the number is less then 999999, should be replaced by the letter 'K'

4000 should be 4K

Can someone help me with this regex ?

enter image description here

Scimonster
  • 32,893
  • 9
  • 77
  • 89
Lucas_Santos
  • 4,638
  • 17
  • 71
  • 118

4 Answers4

3

Note someString has to be a string, not a number.

someString.replace(/0{6}$/, "M").replace(/0{3}$/, "K");
KJ Price
  • 5,774
  • 3
  • 21
  • 34
2

Untested from mobile, but try:

/0{6}$/

Full code:

'4000000'.replace(/0{6}$/,'M')

Addressing thousands:

'4000000'.replace(/0{6}$/,'M').replace(/0{3}$/,'K')
Scimonster
  • 32,893
  • 9
  • 77
  • 89
1

Working Sample for M

The regex used is /0{6}\b/g. Note that $ is not used to check the end of the string, but a word boundary character \b is used which makes this work in a wider range of cases in which other suggestions would fail.

You can very easily derive a similar one yourself for K, leaving that as an exercise for you :)

After you have done that, you can check if your data matches the first regex or not, and replace if it does. If it doesn't, then test for the second regex (for K) and replace if found.

P.S. The service I used to post the solution (Regex 101) is a very useful service and is a perfect tool for prototyping and learning regex.

http://jsh.zirak.me/2klw //see this only if you still can't figure out how to do it.

This spoiler contains the solution if you can't figure out how to do it

user3459110
  • 6,961
  • 3
  • 26
  • 34
0

Another approach that produces exactly the desired output:

function getRepString (rep) {
  rep = rep+''; // coerce to string
  if (rep < 1000) {
    return rep; // return the same number
  }
  if (rep < 10000) { // place a comma between
    return rep.charAt(0) + ',' + rep.substring(1);
  }
  // divide and format
  return (rep/1000).toFixed(rep % 1000 != 0)+'k';
}

I am not taking credit for this answer. This answer was by CMS at a duplicate question found here:

How to format numbers similar to Stack Overflow reputation format

Community
  • 1
  • 1
Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60