Donovan Taitt
Donovan Taitt

Reputation: 11

Regex match characters between two characters NON inclusive in Javascript

I have a url that I want to route to with React router. The id at the end is the part that changes.

https://mywebsite.com/p/foo-bar-fizz-buzz-myid1234

What is the correct regular expression that I need to use in react router? Right now I have the following.

<Route path="(p\/(.*-))":myId component={myComponent} />

Its my understanding that I need to grab the values after the 'p/' up to and including the last dash. I've seen answers involving look arounds but those arent supported in Javascript. How can I accomplish this?

Upvotes: 1

Views: 237

Answers (1)

Luke
Luke

Reputation: 8407

From what I understood, you do want to match everything until the last dash.

That can be accomplished with this expression.

/\/p\/.+\-/
  • match /p/
  • match one or more of any character but line breaks. This will continue as long as it matches.
  • force it to match -, so it will stop the previous expression here.

React Router uses path-to-regexp so your code should work with this solution

<Route path="(p\/(.+\-)):myId" component={myComponent} />

Upvotes: 1

Related Questions