How to insert a space every three characters to a period character?

I am trying to format my inputs to have a space every three characters, right down 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 still have:

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

But this leads to the following:

999999999 => 999 999 999 OK

33333.25 => 333 33.25 NOT OK

222.32 => 222.32 NOT OK

4444 => 444 4 NOT OK

+4
source share
1 answer

You can use this lookahead regex:

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

RegEx Demo

RegEx Distribution:

(?!^)          # 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
+6
source

Source: https://habr.com/ru/post/1609807/


All Articles