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/g, '').replace(/\d{2,3}(?=..)/g, '$&-');
}
console.log(format('00-22 345 991'));
console.log(format('555922134'));
console.log(format('12450-123948'));
console.log(format(123456789));
console.log(format(12345678901));
console.log(format(1234567));