PinoyStackOverflower
PinoyStackOverflower

Reputation: 5302

Javascript Regex to match 2 URLs

I have this kind of URLs that i wanted to match it using RegEx.

  1. "http://example.com/sample/company/123/invoices/download/123a_1a23
  2. "http://example.com/sample/company/123/invoices/view/123a_12a3"

The first 123 is always numeric, while the 2nd 123a_12a3 is alphanumeric and can have an underscore.

I want to create a regex that will check if it will match those 2 URLs above.

I created this code:

let result = new RegExp('\\binvoices/download\\b').test(url);

That works but i think there's a better way to do it to match those 2 URLs and maybe check if those 2 parameters exists, because right now that only matches 1.

I'm new to Regex, so any help is greatly appreciated!

Thanks.

Upvotes: 1

Views: 372

Answers (2)

Phil
Phil

Reputation: 165058

Something like this should match either of those URLs

const rx = /\/sample\/company\/\d+\/invoices\/(download|view)\/\w+$/

const urls = [
  "http://example.com/sample/company/123/invoices/download/123a_1a23",
  "http://example.com/sample/company/123/invoices/view/123a_12a3",
  "http://example.com/sample/other/123/invoices/view/123a_12a3",
  "http://example.com/sample/company/123/invoices/upload/123a_12a3",
]

urls.forEach(url => console.log(url.slice(18), rx.test(url)))

Breaking it down...

\/sample\/company\/ - literal "/sample/company/"
\d+                 - one or more numbers
\/invoices\/        - literal "/invoices/"
(download|view)     - "download" or "view"
\/                  - a literal "/"
\w+                 - one or more "word" characters, ie alpha-numeric or underscore
$                   - the end of the string

Upvotes: 1

bob
bob

Reputation: 8005

Try:

var result = new RegExp('invoices\/(download|view)\/', "i").test(url);

the ( and ) parenthesis with a pipe allow you to check two things.

Upvotes: 1

Related Questions