I'm trying to parse a set of strings that follow the following patterns
{alpha-numeric-id}-{numeric-id}
or
{alpha-numeric-id}/{numeric-id}
- The
alpha-numeric-id
can include the-
character, and numbers - The
numeric-id
is always a number, and is optional. - The
alpha-numeric-id
and thenumeric-id
may either be separated by a-
or/
I want to parse out the alpha-numeric-id
and numeric-id
(if it's there) in a single step.
Examples
'ThePixies1996' => { 1: 'ThePixies1996', 2: '' }
'7ThePixies' => { 1: '7ThePixies', 2: '' }
'The-Pixies' => { 1: 'The-Pixies', 2: '' }
'The-Pixies-1234567' => { 1: 'The-Pixies', 2: '1234567' }
'The-Pixies/1234567' => { 1: 'The-Pixies', 2: '1234567' }
So far the simplest way I have come up with is as follows:
const parse = str => {
const numeric = str.match(/[-\/]([0-9]+)/)
return numeric
? {
numericId: numeric[1],
alphaNumericId: str.slice(0, -1 * (numeric[1].length + 1))
}
: {
numericId: '',
alphaNumericId: str
}
}
Is there a simpler way?