Matching URLs with wildcards in a Chrome Extension using Javascript

I am developing a Chrome extension that enables users to customize content on specific websites. I want to allow users to specify these websites using wildcards, like http://*.google.com or http://google.com/*

While researching, I came across the following code snippet:

currentUrl = "http://google.com/";
matchUrl = "http://*.google.com/*";
match = RegExp(matchUrl.replace(/\*/g, "[^]*")).test(currentUrl);

However, there are some issues with this implementation.

http://test.google.com/ is considered a match

http://google.com/ is not recognized as a match

http://test.google.com is also not identified as a match

http://.google.com/ is matched

Clarification:

http://google.com should be a match, but it isn't in this code execution.

How can I write a JavaScript function that accurately checks for matches?

Answer №1

To enhance the URL validation regex, I recommend breaking down the URL into protocol, base part, and the rest of it. Then, reconstruct the validation regex by replacing '*' within the base part with '(?:[^/]*\\.)*' and other special characters with '\\$&' using

.replace(/[?()[\]\\.+^$|]/g, "\\$&")
. To ensure the regex matches the entire string, include anchors (^ for start of string and $ for end of string position). Additionally, adding a case insensitive /i modifier will make the pattern case insensitive.

For the specific matchUrl provided, the regex would be as follows:

/^http:\/\/(?:[^\/]*\.)*google\.com(?:\/[^]*)?$/

Try out the regex demo here.

var rxUrlSplit = /((?:http|ftp)s?):\/\/([^\/]+)(\/.*)?; 
var strs = ['http://test.google.com/', 'http://google.com/','http://test.google.com', 'http://.google.com/','http://one.more.test.google.com'];
var matchUrl = "http://*.google.com/*";
var prepUrl = "";
if ((m=matchUrl.match(rxUrlSplit)) !== null) {
prepUrl = m[1]+"://"+m[2].replace(/[?()[\]\\.+^$|]/g, "\\$&").replace(/\*\\./g,'(?:[^/]*\\.)*').replace(/\*$/,'[^/]*');
  if (m[3]) { 
      prepUrl+= m[3].replace(/[?()[\]\\.+^$|]/g, "\\$&").replace(/\/\*(?=$|\/)/g, '(?:/[^]*)?');
   }
}
if (prepUrl) {
//  console.log(prepUrl); // ^http://(?:[^/]*\.)*google\.com(?:/[^]*)?$
  var rx = RegExp("^" + prepUrl + "$", "i");
  for (var s of strs) {
    if (s.match(rx)) {
    console.log(s + " is a match!<br/>");
    } else {
    console.log(s + " does not match!<br/>");
    }
  }
}

Answer №2

when using this specific matchUrl

matchUrl = "http://*.google.com/*";

the regular expression appears as follows

"http://.*.google.com/.*"

thus, the goal is to substitute the * input by the user with .* in the regexp match

feel free to utilize this tool for testing purposes

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

Concealing items by placing them strategically between the camera and certain objects in Three.js

At the moment, my project involves utilizing three.js with several objects in the scene. One of the key features I am working on is the ability to select an object and have all other objects between the camera and the selected one hidden or removed. I am ...

The top offset of the select2 search dropdown is not aligning correctly

Encountering a strange problem with a select2 multiple field where the dropdown search message is displaying incorrectly after subsequent searches. Take a look at the issue below: https://i.sstatic.net/9mJo8.png The area highlighted in blue represents th ...

Tips for maintaining the dropdown selection when new rows or columns are added to a table

I have a task requirement where I must generate a dynamic table using jQuery. I've successfully implemented adding dynamic columns or rows to the table. Feel free to check out the fiddle code here. HTML: <div id='input_div' name='i ...

Is there a way to automatically close all open sub-menus when clicking on a different parent menu item?

Check out this LINK for the code I am using. When I click on the Parent Menu, such as Services, the sub-menu of the Services menu will open. However, when I click on another menu, the sub-menu will also open. I want the previous sub-menu to close when I c ...

HTML code for a grid view that allows users to expand and collapse rows in a

I'm looking for a gridview with 'n' rows, each containing 4 columns/items to be displayed. My goal is to accomplish this using an Html/Javascript/Vuejs template exclusively. The desired view should look like this: https://i.sstatic.net/kSx7 ...

Unable to adjust the height of an MP4 video to properly display within a Material Box in both landscape and portrait orientations

While I have been learning JavaScript React, I encountered an issue with positioning an MP4 movie. You can view the code in this Codesandbox If you check out the FileContentRenderer.jsx file, you will see that the html5-video is used for the MP4. The g ...

Exploring Angular 6's nested routes and corresponding components for child navigation

I'm currently diving into the concept of lazy loading in Angular 6. Here's a visual representation of the structure of my application: ─src ├───app │ ├───components │ │ ├───about │ │ ├─── ...

jQuery width property does not seem to be functional on menus that do not contain any dropdown

I am currently working on creating a menu that displays arrows underneath the items when hovered over or when the .active class is added to the menu. Everything is working fine, except for the fact that it only works on menus with drop-downs and the child ...

What are some creative ways to design the selected tab?

In my Vue parent component, I have multiple child components. There are several elements that toggle between components by updating the current data. The issue is that I am unsure how to indicate which tab is currently active. I've tried various li ...

Is it possible to manipulate the carousel image within the div element?

I am working on a Bootstrap code snippet that showcases an image using the w-100 class to span the full width of the page. However, the challenge I'm facing is making sure the image is visible to users while keeping it small enough so they won't ...

Tips on sending parameters from a PHP script to a Javascript file

I am struggling with my new journey into the world of JavaScript. I have been attempting to pass a parameter from a PHP file to a JavaScript file, but for some reason, it's just not working. Here's the code snippet: The JavaScript file is named ...

Tips on initiating a $http.get request every second using a service

I am working on an angular application that includes a $http.get request. While it currently functions properly, I need it to be executed every second in order to retrieve new data. Service: angular.module('adf.widget.liveCharts') .service(&a ...

Preloading and rendering an image onto a canvas in a Vue single-page application is not functioning as expected

I am working on a Vue 3 SPA where I am manipulating canvas elements. To preload my image, I am using the function provided below: async preloadLogo () { return new Promise( (resolve) => { var logo_img_temp = new Image(); const logo_s ...

What is the best way to transfer an integer from my main application to a separate JavaScript file?

Currently, I am developing a complex code using React Bootstrap and focusing on creating a Dropdown list that fetches data from the backend database. <Dropdown> <Dropdown.Toggle variant="success" id="dropdown-basic"></D ...

Issue with Vue.js: Nested field array is triggering refresh with inaccurate information

I've been working on a Vue page where I want to have nested field collections, with a parent form and repeatable child forms. Everything seems to be working fine except that when I try to delete one of the child forms, the template starts rendering i ...

I'm having trouble with my carousel. I suspect it's the "link-rel" in the head tag that's causing the issue

Having trouble with my carousel - it's not navigating properly. When I check the console, it shows: Failed to find a valid digest in the 'integrity' attribute for resource '' with computed SHA-256 integrity 'YLGeXaa ...

Creating a hierarchical tree structure in AngularJS by recursively traversing JSON data

I am having trouble creating a node tree from a JSON file. My index.html file should load the node tree recursively from person.json, but I'm stuck in an infinite loop. Can someone please assist me with this? app.js (function() { var app = angula ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

I am having trouble deactivating an HTML button using my JavaScript function

I have been working on a feature where a button in HTML is supposed to be disabled until a specific textbox is filled out. Once the textbox has content, the button should become enabled and save the user's name along with their score from a previous g ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...