0

How can I reformat this string

0 - 32 1994--245

To

032-199-42-45

I Tried this but my output is wrong

['0 - 32 1994--245'].replace(/[- ]/g, '')
.match(/(\d{1,3})/g)
.join('-')

my output is

 032-199-424-5
aJaysanity
  • 165
  • 1
  • 5
  • 13

2 Answers2

0

Regex

(\d{3})(\d{3})(\d{2})(\d{2})

var str = '0 - 32 1994--245'.replace(/[- ]/g, '')

console.log(str.replace(/(\d{3})(\d{3})(\d{2})(\d{2})/, '$1-$2-$3-$4'))

Demo:

https://regex101.com/r/xnCL8K/1

User863
  • 19,346
  • 2
  • 17
  • 41
0

You could remove all non digits and group by three or two digits.

var string = '0 - 32 1994--245',
    result = string
        .replace(/\D+/g, '')
        .match(/.{2,3}(?=..)|.+/g)
        .join('-');

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392