How do I get a query string from JavaScript?

Asked 2 years ago, Updated 2 years ago, 53 views

Is there a way to get a query string from JavaScript? Should I use jQuery or something like that? Or is it possible only with JavaScript?

javascript url

2022-09-22 08:08

1 Answers

You can only use pure JavaScript.

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

How to write

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
bar bar = getParameterByName('bar'); // " (value is empty)
varbaz = getParameterByName('baz'); // "" (no value)
var qux = getParameterByName('qux'); // null


2022-09-22 08:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.