Is there a way to verify if a capturing group has been involved in the regex or not?

Looking to extract website URLs from text and have a regex in place so far.

((http|https):\/\/)?(www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)

Issue:

If www. is made optional, the regex ends up detecting strings like vue.js or something.ts as URLs and even identifies emails as web URLs. If www. is made mandatory, it fails to detect URLs like this.

The current regex works well for my requirements if I can enhance its flexibility to capture the mentioned URLs.

Query:

I aim to ascertain if the capture group containing http or https has been included in the regex. If the URL includes http, then make www. optional; otherwise, make it mandatory.

Any thoughts on potential solutions to address this challenge?

Answer №1

If my understanding is correct, you are looking to not accept "example.com".

You can make it mandatory for either the "http" (s) or the "www" part to be included in the URL. This way, it becomes a requirement rather than an option. If both are provided, the "www." part will already be matched by the regular expression without any additional considerations needed.

It's worth noting that http|https can be simplified to https?.

Below is the regular expression along with some sample tests:

const re = /(https?:\/\/|www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/

const tests = [
    "http://www.example.com",
    "http://example.com",
    "www.example.com",
    "example.com",
]


for (let url of tests) {
    console.log(re.test(url), url);
}

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

Managing global devDependencies with Node and npm: A comprehensive guide

As I develop a Node module, I have included devDependencies like jasmine-node and jshint that need to be globally installed. My goal is to access their binaries in my makefile / npm scripts without using require(). Despite my research, I'm still unsu ...

Develop a descriptive box for a radio button form using jQuery

I am working on creating a form with simple yes/no questions. If the answer is no, no explanation is needed. However, if the answer is yes, I want to insert a new table row and display a textarea for an explanation. To ensure data validation, I am utilizi ...

Modify select options using JavaScript without losing the selected choice

I am attempting to update the options list of a select element using JavaScript and jQuery while retaining previously selected values. Below is the code I am using: var temp = $('#SelectName').chosen().val(); select = document.getEleme ...

Integrate our JSON data center into the Google Maps API

After retrieving the lat and lng positions from the database, I attempted to replace them in the center JSON object, but encountered an issue. The console displayed the position as {lat:31.752809648231494,lng:-7.927621380715323}, which then led me to conve ...

What could be causing my JavaScript/jQuery code to malfunction when dealing with checkboxes?

My code is supposed to select and disable checkboxes based on which radio button is clicked. For example, when Zero is selected, all checkboxes should be highlighted and disabled, except for the zeroth checkbox. However, this behavior does not consistent ...

The error message "Property 'matches' does not exist on type 'EventTarget'." is displayed on the output of angular-cli

Despite no errors showing up in the Chrome console, the code is functioning properly. constructor() { window.onclick = (event: MouseEvent) => { if (!event.target.matches('.dropbtn')) { const dropdowns = document.getElements ...

"Understanding Global Variables in Javascript and the Impact of Overwriting when Using Splice Method

Struggling with a baffling issue that has me stumped, so any assistance would be greatly appreciated. At the beginning of my script, I establish a global variable called '_raw' (Using jQuery) I execute an Ajax request which returns JSON array d ...

What is the best approach to creating a custom directive in AngularJS that can be used to display a set of items in an

I am a novice in the world of AngularJS and I have set out to create a custom directive that will display specific items from an ng-repeat loop. Here is my current custom directive: (function(module) { module.directive('portfolioList', function ...

Do you have any suggestions on how to send "iframe.contents()" to a PHP Script via Ajax?

I'm currently facing an issue in my code where I have an iFrame loading dynamic content, similar to a webpage (B.html) inside another page (A.php). On "A.php", users can edit the content of "B.html" inline. However, after the editing process is comple ...

Errors in type checking observed in app.reducer.ts file for Angular NgRx

I encountered an issue with my login/logout state management setup. The error message I received is as follows: When trying to assign '(state: State | undefined, action: authActions) => State' to type 'ActionReducer<State, Action>& ...

apply white-space:nowrap to a single column in a datatable

I am facing a challenge with my bootstrap datatable where one row (Product) contains a large amount of data and currently expands downwards, taking up a lot of space. https://i.sstatic.net/BryzM.png My goal is to make the Product column expand to the rig ...

Why is the PageLoad event triggering repeatedly because of the idletimeout plugin?

We encountered a peculiar problem on an asp.net web form project where the page was loading and displaying data (mainly in a gridview). A strange observation was made when setting a break point in the page load event of a specific page. After about 1-2 min ...

The JSON information is not appearing as expected

Utilizing a jQuery function, I am attempting to access a JSON file: $.ajax({ type: 'GET', url: '/data/coffee.json', dataType:'json', success: function(data) { let widget = displayData(data); $(" ...

Error: Attempting to access the 'findAll' property of an undefined value in the context of MariaDB and ExpressJs

TypeError: Cannot read property 'findAll' of undefined findAll function is causing an error, however the Connection was successful. Also, a database named managers has been created. app.js models index.js maria manager.model.js bin ww ...

What is the best way to duplicate all elements and their contents between two specified elements, and store them in a temporary

context = document.createElement("span"); start_element = my_start_element; end_element = my_end_element; // I need to find a way to iterate through a series of elements between start and end [start_element .. end_element].forEach(function(current_element ...

Matching a specific pattern that includes certain strings while excluding others using Regular Expressions

Below is a sample string: var string = "'abc'+@VAL([Q].[F1 w1 w1 w1])+ 'hellllllllllo'+@VAL([Q].[F2 w]) +'anything'+@VAL([Q].[F3 w])+anything"; I am trying to identify the following pattern: @VAL([Q].[F1 w1 w1 w1]) @VAL([Q] ...

Issue with jQuery selection in ChromeI'm experiencing a problem with

After entering a value into an input, I have code that should run when the focus exits the input field. $("#guest-level option[id='"+ result.BookingInfo.guestLevelCode +"']").attr("selected", "selected"); This code runs smoothly in Firefox but ...

Prisma does not automatically update interfaces

I am currently working on a Nest.js project with Prisma as my ORM. However, I have encountered an issue that needs to be addressed: My User model is quite simple: model User { id String @id @default(uuid()) @db.Uuid firstName ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

What is the best way to extract data from a nested array within an array of objects and transfer it to a separate array without altering its nested arrangement?

I have a collection of different objects stored in an array. Each object within the main array contains another array with specific details like this: const data = [ { id: 1, name: "Jack", interests: [ ...