Accomodate multiple values using regex in Javascript

I have regex string /^(?:[)(.*)(?:|)(.*)(?:|)(.*)(?:|)(.*)(?:|)(.*)(?:])$/ that captures the following value [john|doe||doe_avatar|manager]. I also like to capture the value with [john|doe||doe_avatar] using the same regex for both. How can I do that in Javascript?


Yes, this is doable with a single regex, by enclosing the last segment and its accompanying pipe | in an additional, optional, non-capturing group ((?:……)?).

const regex =

const rows = [

const parse = str => {
    const m = str.match(regex)
    if (!m) return null
    const [fullMatch, forename, surname, email, avatar, role] = m
    return { fullMatch, forename, surname, email, avatar, role }


As @CertainPerformance mentions below, the results from the final capturing group will be undefined if the match isn’t present