Reputation: 2166
I have a task that has a few rules. Basically, I am separating a number into groups of 3. If the last group only has 1 digit in it, then the last 2 groups have 2 digits instead of 1 group of 3 and 1 group of 1.
For example:
123456789 = 123-456-789
12345678901 = 123-456-789-01
1234567 = 123-45-67
My regex so far has been:
serial.match(/\d{3}|\d+/g)
where serial is a string passed in via function
function format(serial) {
return serial.replace('/-|/s/g', '').match(/\d{3}|\d+/g).join('-');
}
This gets me the majority of the way there, just doesn't split properly when the last match is {4}.
My progress via fiddle: https://jsfiddle.net/dboots/2mu0yp2b/2/
Upvotes: 2
Views: 101
Reputation: 386519
You can use a regex with lookahead.
The Positive Lookahead looks for the pattern after the equal sign, but does not include it in the match.
x(?=y)
Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.
For example,
/Jack(?=Sprat)/
matches 'Jack' only if it is followed by 'Sprat'./Jack(?=Sprat|Frost)/
matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.
function format(s) {
return s.toString().replace(/\d{2,3}(?=..)/g, '$&-');
}
document.write(format(123456789) + '<br>');
document.write(format(12345678901) + '<br>');
document.write(format(1234567) + '<br>');
Upvotes: 7