Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 546
Amir Avatar asked Oct 01 '15 14:10

Amir


People also ask

How do you put a space in every character in a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!

How do you put a space after 4 characters in HTML input?

CSS text-indent For example, to add an indent of 4 spaces, apply the rule text-indent: 4em; to the element.


1 Answers

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
like image 196
anubhava Avatar answered Sep 30 '22 18:09

anubhava