Develop a regular expression control specifically designed to validate URLs

I encountered a issue with my current web application. When I access the link: https://localhost:44311/#shop, the page loads perfectly as expected. Here is a screenshot: https://i.sstatic.net/6G6CJ.png

However, when I try to change the URL to: https://localhost:44311/#/, in order to test the redirection control, the same content is displayed again without any changes. Here is a snapshot of what occurred: https://i.sstatic.net/Nivm6.png

The problem lies in the fact that all my ajax calls are being triggered repeatedly, leading to an infinite loop.

I have attempted to implement regex control for #/ and respect the pattern #/xxxx/xxxxx, but so far I have been unsuccessful. If you could offer assistance, it would be greatly appreciated!

Below is a snippet of my JavaScript code where I handle the page loading:

var ui = {
   controller: {
       page: {}
   },
   component: {
       category: null
   }
};
ui.controller.pageLoad = function (hash = null) {
   if (hash === null) {
       hash = window.location.hash;
       if (hash.length < 2 || hash[0] !== "#") {
           hash = "/shop";
       }
   } else if (hash.length < 2 || hash[0] === "#" && hash[1] === '/') { // add control regex for #/, must respect #/xxxx/xxxxx
       hash = "/shop";
   }

   $.get(hash.substring(1), function (data) {
       ui.controller.page = null;
       $("#content").html(data);
   }).fail(function (error) {
       $.get("/Home/Error?status=" + error.status, function (data) {
           ui.controller.page = null;
           $("#content").html(data);
       });
   });
};

Answer №1

One way to ensure the validity of a hash is by creating a function called checkHashValidity and implementing it within an if statement:

function checkHashValidity(hash) {
  return typeof hash === "string" && /^#(\/[a-z0-9-]+)+$/.test(hash);
}

function verify(h) {
  console.log(`The hash '${h}' is ${checkHashValidity(h) ? 'valid' : 'invalid'}`);
}

verify(null);            // INVALID - not a string
verify('#');             // INVALID - too short
verify('#shop');         // INVALID - no slash
verify('#/shop');        // VALID
verify('#/shop/item-9'); // VALID

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

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

Button within the Magnific Popup (do not use to close)

I am currently developing a website with a gallery page that utilizes the Magnific Popup plugin. My client has provided lengthy 'captions' for each image, almost like short stories. To display these captions effectively, I have utilized the titl ...

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

What is causing this code to not produce the expected result of 8.675?

Recently, I encountered a challenge on freecodecamp I managed to write the code successfully, but unfortunately, my browser crashed and I lost all the progress. When I attempted to rewrite the code, it was returning an incorrect answer (a value of 2). I& ...

The input field is not displaying the characters I type, despite having a predefined state value in the value attribute

When I input text, it doesn't appear as I type even though I have set the value attribute and it is a controlled input. I've tested this on Stackblitz. My showText useState is set to an empty string. If I change it to just black, I can see the in ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Resizable dimensions for the dark mode switch

My latest project involves creating a toggle button for switching between light and dark themes using CSS, HTML, and JavaScript: id("theme-btn").addEventListener("change", function() { if (this.checked) { qs(".box").setAttribute('style', ...

Incorporating a computed variable in a v-select within a VueJs endless loop

I've been attempting to utilize a computed value in a v-select component from Vuetify, but every time I select an item, it triggers an endless loop. To demonstrate the issue, I have recreated my code in this CodePen. Please be cautious as it may caus ...

Error message: React is unable to locate the map container in the Leaflet library during rendering

I am working with a custom React and Leaflet.js component... export const CustomMapSetLocationComponent = (props) => { React.useEffect(() => { let marker = null let map = null var container = L.DomUtil.get('setLocationMap') ...

Struggling to transfer the loaded data into the corresponding text fields for display

I'm currently working on a project where I need to extract data stored in an object and showcase it on my website. In my .html file, I have the following setup: <script type="text/javascript"> var res = {"address":"","city":"","state":"","z ...

Exploring the Response Object in Express JS: A Comprehensive Guide

I'm currently using Express version 4.13.4. My goal is to access and examine the res object. However, when I try to use console.log() on it, the output is too lengthy to display properly in a command window. I attempted to utilize jsonfile to save i ...

Customizing the Mui Theme in a Unique Way

After generating an MUI component from Mui DatePicker, I encountered the following code: <span class="my-theme-MuiTypography-root my-theme-MuiTypography-caption my-theme-MuiDayCalendar-weekdayLabel css-1mln09i-MuiTypography-root-MuiDayCalendar-week ...

A guide on incorporating dynamic information into JSON files with PHP

I am currently working on developing a checkbox tree where I require dynamic values for checkboxes. Below is my code snippet. Initially, I have static data in JSON format and now I need to retrieve dynamic data from a MySQL database. Despite trying vario ...

The chrome extension is not displaying any output in the console, even though there are no errors

https://i.sstatic.net/YhEKl.png I am currently working on creating a browser extension that will monitor the xhr section of the devtools network tab. To start off, I have kept my background script as simple as possible. Even though there are no errors whe ...

What is the best way to add the ".html" suffix to pages in nuxt.js?

Is it possible to add the ".html" extension to a page address? For instance, changing "test_page" to "test_page.html" ...

Guidelines for redirecting an on-click action to navigate to a link rather than entering text

Using the AJAX Live Search PDO feature, I made a modification to have the displayed words link to their respective URLs. However, clicking on the table does not redirect to the link but instead inputs the text. I am looking for a way to make the entire row ...

Application for Android: Transferring JavaScript Variable to Native Java Variable

I'm developing an Android App and I have a piece of javascript code that is being loaded from "str8red.com" within a webview: <script>var name = "bob", age = 30;</script> There's a textbox in the app that I can set using: textView. ...

Having an issue with a 3D model in the Three.js library while working with React

View the full three.js component here VM90:1 SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON at JSON.parse (<anonymous>) at GLTFLoader.parse (GLTFLoader.js:344:17) at Object.onLoad (GLTFLoade ...

Changing the Material UI imported Icon on click - a step-by-step guide

Hey there, I'm currently working with React JS and Redux. I have a challenge where I need to change the star outline icon to a filled star icon on click. The icon is located just after emailRow in the emailRow__options section. Can someone assist me w ...

Prevent the use of punctuation marks like full stops and commas in GridView Textbox

Within my GridView, there is a column that contains a textbox: <asp:GridView style="width:75%;float:left" ID="gvPieceOutturns" ShowHeaderWhenEmpty="false" CssClass="tblResults" runat="server" OnRowDataBound="gvPieceOutturns_I ...