I need help with regular expressions and formatting

I started having a look at this yesterday, and ended up going down a bit of a rabbit hole, so I put it aside.

Had another look just now and it occurred to me that all you really need to do is strip out all the non-digits and then return the last 9 characters of whatever is remaining. So with that in mind, here is a bit of rough and ready JavaScript that does that. I’m sure it could be improved.

const parts = p1.split('');
let digits = [];
while (parts.length > 0) {
  let bit = parts.shift();
  if (bit.match(/\d/)) {
    digits.push(bit);
  }
}
return digits.slice(-9).join('');

4 Likes