Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get a param from a URL and save it to var else use default

I just tried this JS code to get a parameter from the URL of a website. ?color=#HEXCODE and if there is no param of ?color I want it to apply the default colour.

What am I missing below?

    var color = url.searchParams.get("color");

    if (color) {
        var color = color;
    } else {
        var color = ("#5e46e8");
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const queryString = window.location.search;
console.log(queryString);
//URL?product=bag&color=blue&newuser&size=m

const urlParams = new URLSearchParams(queryString);
const color = urlParams.get('color')
console.log(color);
// blue
if (!color) {
    urlParams.set('color', "red");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading