T-Bone
T-Bone

Reputation: 41

Adding separator to alphanumeric string using RegEx

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.

Upvotes: 1

Views: 324

Answers (2)

TallChuck
TallChuck

Reputation: 1972

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}))

Upvotes: 0

epascarello
epascarello

Reputation: 207527

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'))

Upvotes: 1

Related Questions