Validating URL patterns in JavaScript using Ajax

Below are the ajax urls displayed in a specific format:

http://example.com/v1/components/compId

http://example.com/v1/machine/machineId

http://example.com/v1/graph/startTime=value?endtime=value

http://example.com/v1/graph/startDate=value?enddate=value?startTime=value?endtime=value

I am trying to validate these url patterns using JavaScript. I have applied a regular expression like:

var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

However, it is giving a true result for http://example.com/v1/machine/machineId and

http://example.com/v1 (this should return false).

Please suggest if there is a way to accurately validate the above URLs

Thank you in advance.

Answer №1

Hey there javalearner, if you have a fixed part of your match as http://www.example.com/v1, you can simplify it with the following code:

if (/http:\/\/example\.com\/v1\/[^\/]+\/[\w=?]+/.test(subject)) {
    // You've got a successful match!
} else {
    // Match attempt unsuccessful
}

If that part is not fixed, consider using this code snippet instead:

if (/(?:https?|ftp):\/\/[a-z\d-]+\.[a-z]{2,6}\/[^\/]+\/[^\/]+\/[\w=?]+/.test(subject)) {
    // Match made successfully
} else {
    // Struggle to match
}

Just a heads up, the {2,6} allows for top level domains with up to 6 letters (like com, net), but feel free to adjust for longer or unrestricted TLDs.

If your string ends with other special characters, include them within the brackets in the [\w=?]+ section.

And remember, for case insensitivity, add an i between the final / delimiter and .test, like this: /i.test

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

Strip the pound symbol from the end of a URL during an AJAX request

When I click on the News tab in my Rails application (version 2.3.4 and Ruby 1.8.7), an Ajax call is triggered to load data. <a href="News" onclick="load_feed();"><u>Show More...</u></a> <script> function load_feed() { $.a ...

Troubleshooting problem with personalized WooCommerce Ajax add to cart feature

When attempting to add products (which are only simple products) to the cart using a combination of JavaScript and PHP, I encounter an issue. I send the Product ID(s) and then call the WC_Cart add_to_cart() method in funcions.php. Below is the HTML (and J ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

The Issue of Horizontal Scrolling - None of the elements are out of

I am facing an issue with an unwanted horizontal scroll on my website and I can't seem to identify the cause. The header of my site is quite simple, utilizing display: flex, justify-content: center, marin-top: 5vh, along with some padding on the logo ...

Creating glitchy dotted lines in an HTML Canvas with the help of translate and scale techniques

I'm working on creating a canvas where users can draw symmetrical lines with their mouse. However, when I use the transform and scale attributes in the draw function to achieve this effect, it creates small gaps in the line and makes it look less smoo ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

encountering a problem with npm while trying to execute the project

Encountering a persistent issue when attempting to run my project with npm start, even after downgrading my node version. Despite trying various solutions found on platforms like stackoverflow and stackexchange, such as deleting the node_modules folder, ru ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

How to apply multiple filters in JavaScript?

I have a set of objects that require filtering. If the object has an active status of true, it should always be included in the filtered result regardless of other conditions. If there is text entered for search, then the remaining items should be filter ...

Using jQuery and Ajax to populate a dropdown menu with options

I'm currently working on an ajax call function that successfully fills a drop-down list with data from a specific URL. However, I am looking to modify the function so that it can receive variables in order to populate the drop-down list dynamically. ...

Manipulating global state properties within a reducer function in React: How to do it efficiently

I am looking to implement a single loader (backdrop and spinner) within my app component that can be displayed based on the value of a property in the Redux state called showLoader. This loader should be accessible throughout my entire React application. T ...

Determine the position of the cursor in an editable span

Is there a way to add text at the cursor position in an editable span when a button is clicked? The span contains multiple lines of text and HTML tags. [Take a look at this example on JSFiddle](http://jsfiddle.net/8txz9sjs/) ...

Trouble with Bootstrap modal implementation when using ajax and looping through data

I am having an issue with using the BS modal to display a form containing a select box and updating records in the database via an ajax call. The trigger button to open the modal consists of <i></i> tags with the same class name, itagbtn, and d ...

Tips for removing parameters from rendered XML in Grails

My current challenge involves a specific class: class Category { String name SortedSet items static hasMany = [items:Item] } When it comes to rendering this category as XML in the controller, I am facing an issue: def getCategory = { rende ...

Node/Express unexpectedly returning string instead of Array after parsing JSON file

Having difficulty parsing an empty (stringified) Array from a JSON file. Instead of returning an empty array, I am receiving a string. The initial set up of my JSON file is: "[]" I am storing the parsed data in a variable using File System let parsedOb ...

I'm looking to add multiple markers with multiple info windows using the Google Maps API. How can I achieve this?

Having trouble with the Google Maps API v3? I've set up a map with custom markers, but when clicked they all display the same content in the info window. Can you take a look at my code and help me troubleshoot? Each marker is supposed to link to a spe ...

Integrate ThreeJs models into an Angular JS application

I have a question that pertains to my webapp development. I am currently utilizing Angular Js (v1.5/1.6) and I would like to incorporate some minimalistic 3D animated models by integrating Three Js. Although I have attempted to configure certain aspects, ...

trigger a border hover effect on an HTML element

Is it possible to attach a mouseover event specifically to the left border of a div element in HTML? The div serves as a container for various other intricate HTML elements, each with their own mouseover events. While binding a mouseover event to the enti ...

When a fresh tile is loaded in Mapbox, an event is triggered

As I work with the Mapbox GL JS API to manipulate maps, I find myself wondering if there is an event that can inform me whenever a new tile HTTP request is made. My code snippet looks like this: map.on("dataloading", e => { if(e.dataType ...

Using jQuery ajax to send a Python response back to the original page

I am looking to implement jQuery ajax along with a simple web form containing two fields to transmit values to a python script. The goal is to have the results displayed within a specified div tag on the same calling page (index.html.en). The process invo ...