0

I have a string of digits that's supposed to have 9 characters and I have a regex that replaces the string with the same string and some spaces; something like this:

TheString = '123456789';
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1 $2 $3 $4 $5');
TheSpacedString format is now '1 23 45 67 89'

The problem is that when the length of the string is not 9, the formatting doesn't work: for instance, if we have this:

TheString = '12345';
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1 $2 $3 $4 $5');
format should be '1 23 45'

But instead, the string is just '12345'. What's the problem with my regex? The jsFiddle is here

2
  • 1
    Your regex doesn't match - so of course it does nothing. Commented Dec 3, 2013 at 16:56
  • 2
    You should add validation before you perform your replacement - if you're expecting 9 digits but don't get 9, shouldn't that be an error first? Commented Dec 3, 2013 at 17:05

1 Answer 1

4

Make the last two groups (or however many you think should be optional) optional with ?

http://jsfiddle.net/yWSR2/3/

TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5');
Sign up to request clarification or add additional context in comments.

2 Comments

Oh wow, thanks, fixed my day! Upvoted!! Actually, I added a question mark after each block and it works perfectly!!
Though it will add some trailing spaces like: "1 23 45 " better to call .trim() after this.

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.