Lucas_Santos
Lucas_Santos

Reputation: 4740

Regex to replace a portion of a string

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

Upvotes: 0

Views: 95

Answers (4)

user3459110
user3459110

Reputation: 7061

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

Upvotes: 1

Ian Hazzard
Ian Hazzard

Reputation: 7771

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

Upvotes: 0

Scimonster
Scimonster

Reputation: 33409

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')

Upvotes: 2

KJ Price
KJ Price

Reputation: 5984

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

someString.replace(/0{6}$/, "M").replace(/0{3}$/, "K");

Upvotes: 3

Related Questions