URL value extraction

How can i extract the number 1 in this URL using javascript?


There are a few different ways to do it. I, personally, use document.URL and split on “?” and go from there.

Another way to do it is outlined here.

I think @felgall knows of another way.



location.search contains the part starting from the ? - from there it is then just a matter of splitting on & and = in order to break up the querystring into its component parts.

1 Like

Functions abound to make it easier to retrieve such information, such as:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1),
        vars = query.split('&'),
    for (i = 0; i < vars.length; i += 1) {
        pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) === variable) {
            return decodeURIComponent(pair[1]);
    console.log('Query variable %s not found', variable);

But I prefer to explore other ways, such as by using the reduce method:

function findMatchingValues(parts, value) {
    return parts.reduce(function (values, prop) {
        pair = prop.split('=');
        if (decodeURIComponent(pair[0]) === value) {
        return values;
    }, []);
function getQueryVariable(value) {
    var query = window.location.search.substring(1),
        parts = query.split('&'),
        values = findMatchingValues(parts, value);
    if (!values.length) {
        console.log('Query variable %s not found', value);
    return values;

Thanks for the reply it worked

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.