frenchie
frenchie

Reputation: 51927

javascript regex when diffrent length of string

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

Upvotes: 0

Views: 39

Answers (1)

Matt Burland
Matt Burland

Reputation: 45135

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');

Upvotes: 4

Related Questions