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
  • 5
  • 12

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
  • 18,185
  • 2
  • 15
  • 38
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
  • 351,820
  • 24
  • 303
  • 358