Extracting URLs from a given text string

I came across a regular expression that is supposed to detect URLs but it fails to capture some of them.

$("#links").change(function() {

    //var matches = new array();
    var linksStr = $("#links").val();
    var pattern = new RegExp("^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$","g");
    var matches = linksStr.match(pattern);

    for(var i = 0; i < matches.length; i++) {
      alert(matches[i]);
    }

})

This URL doesn't get captured (I need it to):

However, it does capture this one

Answer №1

Here are a few key points to consider:

  1. The main issue with your code not working is that when passing strings to RegExp(), you need to double up on the slashes. So instead of this:

    "^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$"
    

    You should use:

    "^(https?:\/\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\/\\w \\.-]*)*\/?$"
    


  2. You mentioned that Firefox reported "Regular expression too complex." This indicates that your linksStr likely contains multiple lines of URL candidates.
    Therefore, make sure to include the m flag when calling RegExp().

  3. Your current regex pattern may be blocking valid URLs like "HTTP://STACKOVERFLOW.COM". To allow for case insensitivity, include the i flag in your RegExp() call.

  4. Deal with potential whitespace by using \s* at the beginning and utilizing $.trim().

  5. Are relative links such as

    /file/63075291/LlMlTL355-EN6-SU8S.rar
    permitted?

Combining all these adjustments (excluding item 5), your updated code would look like this:

var linksStr    = "http://www.wupload.com/file/63075291/LlMlTL355-EN6-SU8S.rar  \n"
                + "  http://XXXupload.co.uk/fun.exe \n "
                + " WWW.Yupload.mil ";
var pattern     = new RegExp (
                    "^\\s*(https?:\/\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\/\\w \\.-]*)*\/?$"
                    , "img"
                );

var matches     = linksStr.match(pattern);
for (var J = 0, L = matches.length;  J < L;  J++) {
    console.log ( $.trim (matches[J]) );
}

When run, this will output the following list of URLs:

http://www.wupload.com/file/63075291/LlMlTL355-EN6-SU8S.rar
http://XXXupload.co.uk/fun.exe
WWW.Yupload.mil

Answer №2

What if we try this approach: URLs = str.match(/https?:[^\s]+/ig);

Answer №3

(https?\:\/\/)([a-z\/\.0-9A-Z_-\%\&\=]*)

This regular expression is designed to identify any URL within text.

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

Is there a way I can invoke my function prior to the form being submitted?

For the last couple of days, I've been struggling to make this code function properly. My goal is to execute a function before submitting the form to verify if the class for each variable is consistent. You can access my code here. Any assistance you ...

Controller Not Deserializing Ajax File Upload in MVC 5

There seems to be an issue with deserializing the data sent using the multipart/form-data type within an MVC 5 project. Despite appearing valid in Fiddler, the data is not being mapped into the controller method. While debugging, it is evident that all par ...

What is the best way to replace testcaferc.json browsers using the command line interface (CLI

Scenario: I am facing a situation where I aim to execute Testcafe in docker within a remote environment that necessitates running Testcafe through its command-line interface. I intend to utilize the .testcaferc file that I use for local testing to avoid m ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Creating interactive web pages for scheduling tasks

I'm struggling with how to implement this concept. Imagine I have a School website that features a schedule page for 30 upcoming courses. When a course is clicked, it should lead to a new page displaying specific information about that course (such a ...

Combining multiple JSON strings into a single object using JavaScript

I am facing an issue with parsing a JSON output that contains two strings with specific formats: [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}] [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","senso ...

Update in slide height to make slider responsive

My project involves a list with text and images for each item: <div class="slider"> <ul> <li> <div class="txt"><p>First slogan</p></div> <div class="img"><img src="http://placehold.it/80 ...

Calculating grand total upon form initialization

Hey there! I'm working on an input that fetches values and triggers the fntotal function to show a total. The issue I'm facing is that when the form loads, the total doesn't display initially - it only works when values are changed. <inp ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

How to utilize View as a substitute for the div tag in your Web Project

Undoubtedly, when working on a web project, it is common practice to use the div element like this: <div> sample text </div> However, using div in React Native can lead to errors: <View> sample text </View> Is there a way to ...

Arranging Angular Cards alphabetically by First Name and Last Name

I am working with a set of 6 cards that contain basic user information such as first name, last name, and email. On the Users Details Page, I need to implement a dropdown menu with two sorting options: one for sorting by first name and another for sorting ...

Assign a value to the initial column of a row if the ID is found in the array

I'm attempting to set checkboxes within a specific range. The firebase_id array needs to correspond with column B in that range. If they match, the row should be set to TRUE. However, I am encountering issues where some checkboxes are randomly checked ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

Utilize vue.js to cache and stream videos

I'm new to the world of vue.js and I'm facing a certain dilemma. I implemented a caching system using resource-loader that preloads my images and videos and stores the data in an array. Everything is functioning correctly, but now I'm unsur ...

I am looking to build an array that can store five numbers inputted by the user. Following that, I want to utilize a for loop to display the contents of the array. How can I accomplish this task?

Looking for help to store 5 unknown numbers in an array and then display them after the user has entered all 5 numbers. Can anyone assist me in creating an array of size 5 and using a for loop to show the numbers? Here is the code I currently have: ...

There is an issue with the sorting function: [orderBy:notarray]. The expected input was an array

Looking to incorporate pagination functionality from this source: http://jsfiddle.net/SAWsA/11/ [ { "name": "Micro biology", "id": "2747c7ecdbf85700bde15901cf961998", "category": "Other", "type": "Mandatory - No Certification", "cate ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

Error: The reference property 'refs' is undefined and cannot be read - Next.js and React Application

Here is my code for the index page file, located at /pages/index.js import { showFlyout, Flyout } from '../components/flyout' export default class Home extends React.Component { constructor(props) { super(props); this.state = {}; } ...

The information retrieved from the API call did not meet my expectations; instead, it returned as undefined

In my development project, I have organized my functions in a file called PostApi.js. In another file, Posts.js, I make the call to these functions. However, when using api.getPosts() and data in the Posts.js file, I encounter an issue where it returns un ...