Home > database >  Adding separator to alphanumeric string using RegEx
Adding separator to alphanumeric string using RegEx

Time:03-10

I have a string as : A123456789BC

And I would like the output to be : A-123-456-789-BC for display purposes.

I am using a regex in replace function but so far it only does : A-123-456-789BC

This is what I have -

String.replace(/(\d{3})/g, (found) => {return '-' found});

Basically if I have an alphanumeric string as above, I would like the numbers to be grouped in 3 and add separators(-) to their start and end.

Would appreciate any help to achieve this.

CodePudding user response:

Add a match for the ending and you should have it. So match 3 numbers or two characters at the end.

console.log('A123456789BC'.replace(/(\d{3}|[A-Z] $)/g, '-$1'))

CodePudding user response:

I would update your regular expression like this:

String.replace(/(\d{3}|(?<=\d{3})\D)/g, (found) => {return '-'   found})

This will not only add a hyphen before a group of 3 digits, but also before a non-digit character following a group of 3 digits.

console.log('A123456789BC'.replace(/(\d{3}|(?<=\d{3})\D)/g, (found) => {return '-'   found}))

  • Related