Using JavaScript to Capture URL Parameters as Variables

Similar Question:
How to retrieve query variables using JQuery?
Retrieve query string values in JavaScript

If my website's URL is

(where both parameters are URLs)

What I want to achieve now is extracting two javascript variables from the site, each containing the values of the respective URLs. For instance, the first variable would hold testsite.com, and the second one would have sample.com [including http and all, but only one hyperlink can be displayed]

How can this be accomplished?

I came across similar inquiries on this platform where users proposed complex solutions involving finding '=' and extracting everything after it, which left me puzzled. In this case, such a method would result in "http:// www.testsite.com&r= [excluding spaces]" as one of the variables.

Another user had multiple parameters like mine, but their solution was too convoluted for me to comprehend how to customize it for my needs.

Therefore, could someone provide guidance on how to solve this issue?

Answer №1

Give this code a try:

function extractQueryParameter(url, parameterName) {
    var query = url.substring(url.indexOf('?')+1);
    var params = query.split('&');
    for(var i = 0; i < params.length; i++) {
        var param = params[i].split('=');
        if(param.length > 1) {
            if(param[0] == parameterName) {
                return param[1];
            }
        }
    }
    return null;
}

console.log(extractQueryParameter('http://www.akbrowser.tk/ds/?q=http://www.chess.com&r=http://www.blackle.com', 'r'));

Answer №2

const getValueFromUrl = (key) => {
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    const regexStr = "[\\?&]" + key + "=([^&#]*)";
    const regex = new RegExp(regexStr);
    const results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

const queryString = getValueFromUrl("q");
const searchString = getValueFromUrl("s");

This function uses regular expressions to extract the value of a specific parameter from the 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

Utilizing Three.js to Upload Images and Apply Them as Textures

While attempting to upload an image via URL and set it as a texture, I encountered an issue. The error message THREE.WebGLState: DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': Tainted canvases may not be loaded ...

What is the process for animating the rotation of my FBX model using the animate function?

I'm trying to figure out how to create a continuous rotation for my FBX model using three.js. Here's what I've attempted so far: Declared my object as a variable Called my object in the animate function for rotation (girl1) However, I enc ...

Utilize the onClick Event to Trigger Function with an Array in ReactJS

Every time I attempt to pass an array as a value to a function by clicking on a div, I encounter the error below: Uncaught Invariant Violation: Expected onClick listener to be a function, instead got a value of object type. If passing an array to a fun ...

Exploring options for accessing Google Maps API on iPhone without using UIWebView for processing JavaScript

I need to retrieve data from Google Maps using JavaScript, without using a webview. For example, I have two points (lat,lng) and I want to use the Google Maps API to calculate the driving distance between them. Essentially, I want to utilize the Google Ma ...

Eliminating repeated entries in MongoDB

Hey guys, I've been struggling for days trying to eliminate all the duplicates from my database. I attempted a solution I came across on this Link, but encountered an error message stating that forEach is not a function. I'm puzzled as to why it ...

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...

Retrieve data using $http.get when an accordion group is expanded in AngularJS

Currently, I am utilizing Angular v1.2.0rc1 along with Angular-UI Bootstrap. [edit] My objective is to implement a load-on-demand feature with caching while incorporating an accordion functionality. The accordion group that I am using can be found here. ...

Establish the directive upon receiving the broadcast

Is there a way to trigger a directive when a specific event occurs on the backend and sets a value to false?... This is where the event is being captured .factory('AuthInterceptor', function($q, $injector, $rootScope) { return { ...

scrolltop function is unable to reach the end of the div

I am attempting to achieve the following: When the button is clicked, the div will be displayed and you will automatically scroll to the bottom of the page. While my other attempts have been successful, this particular one does not seem to be working. Coul ...

avoiding the need to download additional audio files when the play() function is executed

I have encountered a strange issue with my audio files. When I trigger the function 'setCurTime37()', it plays the correct audio file ('myAudios1') as expected. However, it also initiates the downloading of the second audio file (' ...

Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you. My project involves creating a web application f ...

Properly showcasing commas

Need help adding commas to numbers. Currently, my output is 1,2,3,4,5,6,7,890 but I want it to be 1,234,567,890. I am using keyup which is causing some problems. Any suggestions? numberWithCommas : function () { var target = $("#foo"); target.val(targ ...

What is the best way to apply a function to every value of a property within a javascript object?

I have an object structured like this. It will continue with more children blocks in a similar format. My goal is to replace the value of "date" throughout the entire object with a version processed through NLP. { "date": "next friday" ...

What is the reason for the absence of Duplex Stream in the Web Streams API?

I have experience working with the traditional nodejs stream, which makes the need for Duplex streams quite evident. These are streams that can both read and write data, like net.Socket. As mentioned here Examples of Duplex streams include: TCP sockets ...

Using Firebase Authentication on Your Website

I am currently working on developing a login system using Firebase authentication and I have encountered some issues in the process. After following Google's tutorial (https://www.youtube.com/watch?v=rQvOAnNvcNQ), and creating a simple "Index.html" & ...

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

Issue: Unable to navigate the dependency graph: Module '@badeball/cypress-cucumber-preprocessor/steps' cannot be located

Encountering an error when running my feature file and unsure of the issue. See screenshots below: https://i.sstatic.net/Ks5Sy.png https://i.sstatic.net/BP4rl.png https://i.sstatic.net/8IoMM.png ...

Using Jquery to Create a Dialog Box and Retrieve Data from a Database

Hey everyone! I'm currently tackling a section of a website that involves retrieving data from a database table and displaying it sequentially using previous and next buttons within a JQuery Dialog box. I'll admit, I'm not the most skilled ...

Creating a Discord Bot: Building an Embed Table/List with Segmented Sections

Currently in the process of learning Javascript and venturing into discord.js, I'm fully aware that the code I am working with is not up to par and requires some serious refinements. The main objective here is to split up the arguments of a command a ...

Generating duplicate HTML code and updating the content ID based on the currently selected tab

I have three Tabs "B1", "B2", and "B3". I am looking to duplicate this HTML structure and insert it into the content of three tabs with the specific ids id = "bv-B1-p1", id = "bv-B2-p1", and id = "bv-B3-p1" (essentially replacing -brand- with B1, B2, or ...