2

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/

3
  • Is your goal to produce a new string ("formatting") or really to extract the matchs ? Commented Apr 8, 2016 at 11:57
  • I would be producing a new string via .join() on the match. I'll update question to provide clarity. Commented Apr 8, 2016 at 12:03
  • Why not just check the length of the string, and then slice accordingly? Commented Apr 8, 2016 at 12:10

1 Answer 1

7

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

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

4 Comments

@Wiktor: That's more letters :-)
Thanks so much for the quick reply. I was looking into lookaheads, but after looking at your answer, I was doing them wrong! This works perfectly! Could you explain how the lookahead is working with ..? I was attempting (?=\d{2}).
Oh perhaps I had a ?=(if) then|else. So this statement says if it's a group of 2-3 numbers it's a match and if the next group is 2 numbers, make that a match as well, therefore ending the regex?
kind of, but there is no else.

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.