user3403708
user3403708

Reputation: 35

How can I pass a value in a URL and insert value in a new URL to redirect with Javascript?

I am passing a value in a URL in the form of http://example.com/page?id=012345. The passed value then needs to be inserted in a new URL and redirect the page to the new URL. Here is what I have been working with

function Send() {
    var efin = document.getElementById("id").value;
    var url = "https://sub" + encodeURIComponent(efin) + ".example.com" ;
    window.location.href = url;
};    

Upvotes: 0

Views: 146

Answers (1)

Shiny
Shiny

Reputation: 5055

Sounds like you're looking for the features of URLSearchParams - Specifically using .get() to fetch specific parameters from the URL

// Replacing the use of 'window.location.href', for this demo
let windowLocationHref = 'http://example.com/page?id=012345';

function Send() {
    let url = new URL(windowLocationHref);
    let param = url.searchParams.get('id');

    let newUrl = "https://sub" + encodeURIComponent(param) + ".example.com" ;
    
    console.log('Navigate to: ' + newUrl);    
    //window.location.href = newUrl;
};

Send();

Upvotes: 1

Related Questions