Regular expression for matching URLs with either one or two segments in the path component

Looking for a regex to match the first two lines of this URL/path structure, but not if there's a third path included. Any suggestions?

http://somewebsite.foo/aaa
http://somewebsite.foo/aaa/bbb
http://somewebsite.foo/aaa/bbb/ccc

Answer №1

A more efficient alternative to regex is utilizing the URL and split functions

let a = 'http://somewebsite.foo/aaa'
let b = 'http://somewebsite.foo/aaa/bbb'
let c = 'http://somewebsite.foo/aaa/bbb/ccc'

let test = (input) => {
  return new URL(input).pathname.split('/').length < 4
}

console.log(test(a))
console.log(test(b))
console.log(test(c))

Answer №2

There are 3 matches because the regex \/aaa(\/.*|) finds 3 instances of 'a' and captures a forward slash followed by any character in a capturing group from /aaa to the end of the string.

To match the entire URL, you can start by matching the beginning of the URLs and use a negated character class [^\/] to find anything except a forward slash, making the second part optional.

^https?:\/\/[^\/]+\/[^\/]+(?:\/[^\/]+)?$
  • ^https?:\/\/ Matches the beginning of the URL
  • [^\/]+\ Matches one or more characters that are not a forward slash
  • /[^\/]+ Matches the first occurrence of / followed by a non-/ character
  • (?:\/[^\/]+)? Uses the same pattern but makes it optional with a non-capturing group
  • $ Denotes the end of the string

View demo on regex101

If the requirement is to match 'aaa' and 'bbb', you can use:

^https?:\/\/[^\/]+\/aaa(?:\/bbb)?$

[
  "http://somewebsite.foo/aaa",
  "http://somewebsite.foo/aaa/bbb",
  "http://somewebsite.foo/aaa/bbb/ccc"
].forEach(x => console.log(x + " ==> " + /^https?:\/\/[^\/]+\/[^\/]+(?:\/[^\/]+)?$/.test(x)));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to show personalized messages to users using modal windows?

Encountering bugs while trying to implement user messages in modals. function displayMessage(title, description) { var myModalErrorMessage; $("#customErrorMessageTitle").text(title) $("#customErrorMessageDescription").html(description) myModalEr ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

Configuring the text box to utilize jQuery's datepicker feature

Currently, I am facing an issue with setting up a datepicker in a dynamic control creation scenario. The control is being created on the fly, causing inconsistencies with the id, which in turn is preventing the datepicker from functioning properly. Here is ...

Is it feasible to trigger a dialog box by clicking on a textField within MaterialUI?

Is there a way to create a clickable textField that opens a dialog box for users to input more text? I'm specifically looking for a solution using MaterialUI. Currently, I have a workaround where a button is displayed to open the dialog box instead o ...

What makes long polling to an asp.net mvc app necessitate using the POST instead of GET ajax method?

Currently, my team and I are working on replicating a demo app showcased by Steven Sanderson in his SignalR demonstration, specifically focusing on the long polling feature. While the demo is functioning properly, we have encountered an issue when switchin ...

Tips for retrieving sent data from a jQuery Ajax request on XHR error

I am facing a situation where I have numerous jQuery AJAX requests being sent using a single function. function sendData(data){ $.post("somepage", {"data": data}, function() {}, "json") .fail(function(jqXHR, textStatus, errorThrown){ sendD ...

Align the reposition button with the pagination in the datatables

I am looking to adjust the placement of my buttons. The buttons in question are for comparison, saving layout, and printing. I would like them to be inline with the pagination, as I am using datatables here. <table id="sparepart_id" cellspacing="0" ...

Customizing CoreUI column names in Vue

I am working with an array of item objects for a table. For example: [{ name: 'Sam', age: 24 }] Instead of using the default column names like age, I want to set custom field names. For instance, I want to display the column as Id instead of age ...

Upon refreshing the browser page, AngularJS fails to redirect to the default page as expected

In my AngularJS route configuration, I have set up the following paths: moduleA.config(function($routeProvider){ $routeProvider. when('/A',{templateUrl:'A.jsp'}). when('/B',{templateUrl:'B.jsp'}). wh ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

Challenge with dynamic parent routes

In my React application, different routes are loaded through various parent URLs. For example: {["/sat/", "/act/", "/gre/", "/gmat/", "/toefl/"].map((path) => ( <Route key={path} path={path ...

Reorder the placement of file inputs that have been prepended

Would it be feasible to have the prepended file input display below the preceding element rather than above it? This way, the "Select a file:" text would remain at the top of all newly added elements. $(document).ready(function(){ $(' ...

The final DOM is not loading properly when using Jest and React Testing Library during page initialization

I'm currently working on testing my React application with Jest and React Testing Library. During this process, I am attempting to verify that the login page displays a specific message once it has fully loaded. Upon initial loading of the login page, ...

Overriding Methods in a Node Module

I have been utilizing the keystone node module to create cms-based pages in my application. To initialize Keystone, I simply add it to my JavaScript file like this: var keystone = require('keystone'); The issue I am currently facing is that th ...

What is the best way to retrieve data from a JavaScript function and store it in a user's custom meta field using PHP?

Currently, I am utilizing a platform that automates the device registration process for my users through Onesignal. Upon user login, I invoke the function by using gonative_onesignal_info(); within script tags (the full function is provided below). This s ...

Add CSS styles to the outermost container element when the slideshow is currently in use

On my homepage, I have a carousel featuring multiple slides. However, when the third slide appears in the carousel, the positioning of the carousel buttons within the div class="rotator-controls" shifts downward due to the space taken up by the image. My o ...

Animating CSS with jQuery for a background image effect

I have the following JavaScript code : $(".linksColl a li").hover(function () { $(this).css({ "background-image" : "url(images/links/linkHover1.png)", "background-position" : "center center", ...

handlebars and expressjs having trouble displaying the data

Hey there! I'm currently working on an application with express.js and handlebars. I've set up a get method to retrieve employee data when the user enters http://localhost:3000/id/2 in their browser. The id should be 2, and it's supposed to ...

Is it possible to adjust the element's position using the code "element.style.top = window.scrollY"?

Recently, I attempted to create a floating input element that would follow the scroll. After much effort, I managed to achieve it and the code is provided below. However, I encountered an issue when trying to change "setText(window.scrollY)" to ...

What is the most effective way to accurately identify the mobile platform of a user using JavaScript?

I need to determine whether a user has accessed the application through a browser on Android or iOS. The company would like to display slightly different content depending on the platform. While I am aware that navigator.platform can be used for this pur ...