Retrieve a URL from a string using Javascript

After hours of searching, I'm still stuck on this issue that seems like it could easily be solved with a quick Google search.

Basically, I have this string that I'm ajaxing from another site:

'function onclick(event) { toFacebook("http://www.domain.com.au/deal/url-test?2049361208?226781981"); }'

It looks like this because I'm extracting the onclick.

All I want to do is extract the URL from the string.

Any assistance would be greatly appreciated.

---- edit ----

If I go to http://regexlib.com/RESilverlight.aspx online regex tester

and use this regex:

(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

it perfectly highlights the URL in my string. I just can't figure out how to make it work with JavaScript?

Answer №1

Assuming the input always includes a dash, you can extract everything before the dash using the split method:

var data = split(value);

The desired value will now be stored in the array at index 0.

Answer №2

Below are two JavaScript functions that can be used:

function extractUrlData1(data) {
var pattern = /^((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/;

if (data.match(pattern)) {
    return  {url: RegExp['$&'],
            protocol: RegExp.$2,
            host:RegExp.$3,
            path:RegExp.$4,
            file:RegExp.$6,
            hash:RegExp.$7};
}
else {
    return  {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}

function extractUrlData2(data) {
var pattern = /((http|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?/;

if (data.match(pattern)) {
    return  {url: RegExp['$&'],
            protocol: RegExp.$2,
            host:RegExp.$3,
            path:RegExp.$4,
            file:RegExp.$6,
            hash:RegExp.$7};
}
else {
    return  {url:"", protocol:"",host:"",path:"",file:"",hash:""};
}
}

Source: http://lawrence.ecorp.net/inet/samples/regexp-parse.php

Answer №3

I found myself doing this in the end

$a.substring($a.indexOf("http:"), $a.indexOf("?"))

I struggle with understanding regular expressions.

Answer №4

If you use yourFunction.toString().split("'")[1], it will get the job done.

Answer №5

 const linkPattern = /(http?:\/\/[^\s]+)/g;

    const matches = inputValue.match(linkPattern);

    if (matches === null) {

    return "";

    } else {

    const foundLink = matches[0];

    return foundLink;

     }

Answer №6

Update: I have found an alternative solution to extract the URL:

var clickFunction = 'function onclick(event) { toSocialMedia("http://www.example.com/deal/test-url?2049361208?226781981"); }'
clickFunction.match(/(http:[^"]+)/)[0]

Previous response: Utilize Regular Expressions:

javascript regex to extract anchor text and URL from anchor tags

var linkRegex = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;

alert(linkRegex.test("http://example.com"));

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

Problem with HTML relative paths when linking script sources

Having trouble with a website I constructed using Angular. The problem lies in the references to javascript files in index.html. The issue is that the paths in the HTML are relative to the file, but the browser is searching for the files in the root direct ...

Accessing objects from a loop in JavaScript

In an effort to adhere to the principle of avoiding "polluting the global namespace" and due to the consensus that global variables are typically discouraged, I made a modification in my code by replacing global variables: stBgAsset15_src = $image.at ...

What is the best way to design an angular directive or service specifically for straightforward pagination featuring only next and previous options?

Within a block of div tags, an ng-repeat directive is being used to display sets of 3 divs at a time. By clicking on the next button, the next set of 3 divs should be displayed, and the same goes for the previous button. Check out the HTML code below: &l ...

Tips for displaying the node's label in Arbor js when hovering over the node

I'm currently utilizing Arbor Javascript to exhibit a graph composed of nodes and edges. My objective is to have the node's label displayed when the mouse hovers over it within the graph. Below is the code snippet I am working with: <canvas i ...

Is there a way to locate the source or URL linked to a button on a form or webpage?

Currently, I am extracting data feeds from a webpage by clicking a button that is similar to the 'Login' button displayed on the following link: However, this button acts as a 'Download' request that initiates the download of a csv rep ...

What is the best way to send form data to MongoDB using React?

I am seeking guidance on how to pass the values of form inputs to my MongoDB database. I am unsure of the process and need assistance. From what I understand, in the post request within my express route where a new Bounty is instantiated, I believe I need ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

A method for automatically refreshing a webpage once it switches between specific resolutions

On my page www.redpeppermedia.in/tc24_beta/, it functions well at a resolution of over 980px. However, when the resolution is brought down to 768px, the CSS and media queries alter the layout. But upon refreshing the page at 768px, everything corrects itse ...

Error in Javascript programming | tracking progress bar

After stumbling upon this code snippet at this link, I was eager to delve deeper into the world of JavaScript and jQuery. However, upon implementing these codes, I encountered a perplexing issue. The progress bar and continue buttons seem to be non-funct ...

The materialLoader in Three.js is experiencing difficulty loading an embedded texture image

When I export a material from three.js using the material.toJSON() method, I receive the following result: { "metadata":{"version":4.5,"type":"Material","generator":"Material.toJSON"}, "uuid":"8E6F9A32-1952-4E12-A099-632637DBD732", "type":"MeshStandardMat ...

Include a class above the specified element; for instance, apply the class "act" to the "<ul>" element preceding the "li.item1"

Hello there! I need some assistance, kinda like the example here Add class and insert before div. However, what I really want to do is add the class "act" to a class above that matches the one below: Here's how it currently looks: <ul> ...

Exploring the World of JSON Nested Arrays with Unknown Titles and Organizing Them for Storage

Apologies if this question has already been addressed elsewhere, but I couldn't find it. I have a JSON object with dynamic keys: { "main": [ { "Example1": [ { "Example1_Var02": "5", ...

Is the execution of promises in Node.js synchronous or asynchronous?

There is a lot of confusion regarding promises. Are they synchronous or asynchronous? return new Promise (function(resolved,reject){ //Is this operation synchronous or asynchronous? }); ...

Displaying a subset of categories based on the user's selection

I have been trying to find a solution to automatically display a subcategory select drop-down only when a user selects a category. If no category is selected, the subcategory drop-down should remain hidden. I have searched online tutorials and videos for ...

Ways to execute the pdf.js node demonstrations?

I've been attempting to run the pdf.js node examples, specifically getinfo.js. Unfortunately, I encountered an issue that resulted in the following error: C:\Repositories\pdf.js>node getinfo.js node:internal/modules/cjs/loader:1080 thro ...

Embarking on a New Project with Cutting-Edge Technologies: Angular, Node.js/Express, Webpack, and Types

Recently, I've been following tutorials by Maximilian on Udemy for guidance. However, I have encountered a roadblock while trying to set up a new project from scratch involving a Node/Express and Angular 4 application. The issue seems to stem from the ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

How should one go about creating an npm package out of a vuejs component and testing it locally?

Initially, I created a vuejs project as a test container using vue-cli. Next, I developed an npm package named "vue-npm-example" from a Vuejs component in my local environment and then imported it into the aforementioned testing project. Within the packag ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

The issue of JQuery Mobile not recognizing HREF links when combined with Javascript

I am facing a challenge with my button functionality that is supposed to open a panel. However, there seems to be an interference caused by my JavaScript code. The panel contains a notifications center and in order to retrieve the notifications, I have to ...