7

I've been trying to format my inputs to have a space every three characters, up to the period character.

For example:

999999999 => 999 999 999

33333.25 => 33 333.25

222.32 => 222.32

4444 => 4 444

Here is what I have so far:

$(this).on('keyup', function(){
            $(this).val( $(this).val().replace(/(\d{3})(?=.)/g, "$1 ") ); 
        });

But this results in this:

999999999 => 999 999 999 OK

33333.25 => 333 33.25 NOT OK

222.32 => 222 .32 NOT OK

4444 => 444 4 NOT OK

Tushar
  • 85,780
  • 21
  • 159
  • 179
Amir
  • 4,211
  • 4
  • 23
  • 41

1 Answers1

11

You can use this lookahead based regex:

str = str.replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ');

RegEx Demo

RegEx Breakup:

(?!^)          # Assert we are not at start of line
(?=            # start of positive lookahead
   (?:\d{3})+  # assert there are 1 or more of 3 digit sets ahead
   (?:\.|$)    # followed by decimal point or end of string
)              # end of lookahead
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 2
    Wow! I was thinking about - split reverse join regex split reverse join aah! – Tushar Oct 01 '15 at 14:24
  • I wish I knew regex too :( --do you recommend any document to learn it from? – Gui Imamura Oct 01 '15 at 14:37
  • 1
    I broke your regex, mate. It took me a while of poking but I had this feeling that I could. And I did. *"0.123456".replace(/(?!^)(?=(?:\d{3})+(?:\.|$))/gm, ' ')* screws it up. However, you've got my undivided awe and respect for this regex-fu. +1 – Konrad Viltersten Dec 02 '16 at 21:23
  • Good catch. My assumption was that there are not more than 2 decimal digits. For a fix of your example [you can use this in PCRE](https://regex101.com/r/xF1oZ5/3) but in JS one should split on DOT and use regex in my answer on 1st part only. – anubhava Dec 02 '16 at 21:50
  • Is it possible to limit decimal up to 2/3 digits only. – Amit Jamwal Dec 05 '17 at 12:42
  • Sample input like 12233233.333 and output is like 12 233 233,33 only. – Amit Jamwal Dec 06 '17 at 05:33
  • That will require PCRE regex not Javascript. In PCRE use this: https://regex101.com/r/xF1oZ5/17 – anubhava Dec 06 '17 at 07:37