2

I've got this regex:

(/(\d{2})(\d{3})(\d{2})/g;

What I want to do is to replace every 2, when every 3 and when every 2 again character with a " " while typing. Which means if I type "123" it should be formatted to "12 3" and if I type "12345" it should be formatted to "12 123 "

However I get a spacing only after every 7 character. Here's a jsfiddle: http://jsfiddle.net/K4WXc/257/

Help would be highly appreciated!

5
  • What should be output for 123456 and 1234567, 123465789? Commented Aug 2, 2016 at 12:29
  • Try return v.replace(/\d(?=(\d{3})+$)|^\d(?=\d{2}$)/g, "$& "); and let know if that meets your requirements. Commented Aug 2, 2016 at 12:31
  • @Tushar 'the pattern is "xx xxx xx" so if I type 123456 it should look "12 345 6" in the input. If I type 1234567 it should be "12 345 67 " and for 123465789 it should be "12 346 57" (i'll update my jsfiddle with a maxlength property of 7 so it won't be possible to type a longer string). Commented Aug 2, 2016 at 12:41
  • @WiktorStribiżew thanks for your help! if I type "111" it becomes "1 11" and it should be "11 1". It becomes correct when I type 5 numbers though - "11 111". But for six numbers it becomes "111 111" when it should be "11 111 1" Commented Aug 2, 2016 at 12:42
  • Try v.replace(/^(\d{2}) ?(\d{3})?(?=\d)/g, "$1 $2 "); Commented Aug 2, 2016 at 12:49

1 Answer 1

1

I have modified your fiddle as shown below:

    return v.replace(/^(\d{2})(\d{1,3})(\d{0,2}).*/, function (match, a, b, c) {
        return a + ' ' + b + (c == '' ? '' : ' ' + c);
    });

Keeping in mind that just before this block, you have removed any non-digits, this block expects just digits (no spaces).

It matches 2 digits at the beginning: ^(\d{2})

Then 1 to 3 as the next capture group: (\d{1,3})

If there are 3 in that 2nd group, it will capture up to 2 more: (\d{0,2})

Anything more than that will be discarded: .*

The important part of this that enables it to match "incomplete" entries as you type is that it matches even if you haven't typed all 3 digits of the 2nd group, or both of the 3rd group.

NOTE: the main problem with your original replace was the missing first param that represents the whole matched string.

Sign up to request clarification or add additional context in comments.

1 Comment

I modified the code to accept a data parameter for the input filter: jsfiddle.net/MrPolywhirl/K4WXc/263

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.