skip to Main Content

I am trying to match this.

/1234/5678
/1234

Into A and B, where the B is optional using this regular expression.

/.*/(?<A>d+)(/(?<B>.+?))?$/.exec("/1234/5678").groups;

I want A=1234, and B=5678 when the path contains two parts, and when there’s only one part, then just match A.

How do I make the optional /5678 greedy so that it matches if it’s there, but still matches A if it’s not.

/1234/5678 (A=1234, B=5678)
/1234 (A=1234, B=undefined)

2

Answers


  1. You can try this.

    console.log(/(?:/(?<A>[^/]+))?(?:/(?<B>[^/]+))?/.exec("/1234/5678").groups);
    console.log(/(?:/(?<A>[^/]+))?(?:/(?<B>[^/]+))?/.exec("/1234").groups);
    Login or Signup to reply.
  2. There’s no need in a regular expression, you can just split the string and use array destructuring:

    {
     const [_, A, B] = '/1234/5678'.split('/');
     console.log({A, B});
    }
    {
     const [_, A, B] = '/1234'.split('/');
     console.log({A, B});
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search