Reputation: 5302
I have this kind of URLs that i wanted to match it using RegEx.
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
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
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