Only get a part of a url

Asked

Viewed 3,553 times

2

5 answers

3


Use the function split() of Javascript, thus:

NOTE: The example will print an Alert Undefined because there is no url with parameter "? ip=", but test with its url that will work.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
            <script>                                        
              var url = window.location.href;
              url = url.split('?ip=');
              url = url[1];
              alert(url);
            </script>
    </body>
</html>

1

ES2015 (ES6)

const getParams = query => {
  if (!query) {
    return { };
  }

  return (/^[?#]/.test(query) ? query.slice(1) : query)
    .split('&')
    .reduce((params, param) => {
      let [ key, value ] = param.split('=');
      params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
      return params;
    }, { });
};

Without jQuery

var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

With the URL ?topic=123&name=query+string, the return would be:

qs["topic"];    // 123
qs["name"];     // query string
qs["nothere"];  // undefined (object)

1

Javascript has by default this information in window.location and to get the value more easily you can use the URL class.

var url = new URL(window.location);
var ip = url.searchParams.get("ip");

The value will be in the variable ip.

  • 1

    Very practical, works in all current browsers?

  • From what I saw in the Mozilla documentation Internet Explorer does not run https://developer.mozilla.org/en-US/docs/Web/API/URL/URL Microsoft Edge if it does not run yet, it will run, because there is an Issue on their website that says it will be implemented in the next updates.https://Developer.microsoft.com/en-us/microsoft-edge/Platform/issues/8993198/

  • https://caniuse.com/#feat=urlsearchparams This table places Edge from version 17

  • 1

    Sorry, in my example I use the URL class and not Urlsearchparams. So Edge already supports yes https://caniuse.com/#feat=url

  • Oh wonder, I haven’t explored all the possibilities in various browsers, mainly EDGE, but still thank you for clarifying.

1

The javascript function below returns an array/object with the parameters and values of the current url variables.

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Ex:http://leituracrista.com/audioplayer/player.html?ip=dispensacao#15&site=leituracrista

calling the function getUrlVars(), considering the above url, we will have the following return:

{
    "ip"    : "dispensacao#15",
    "site" : "leituracrista"
}

to take the value of the first parameter would be like this:

var first = getUrlVars()["ip"];      //dispensacao#15

the second:

var second = getUrlVars()["site"];   //leituracrista

Source

0

Try it like this, and see if it fits:

window.location.search
  • this returns me "? ip=waiver" but did not want the ? ip= and wanted to ask fnal of the url tbm

  • So, but there’s a problem. When you put that # at the end, the browser understands it as an anchor. That’s why it doesn’t come in value. I recommend you take out the # and put an _ or something like that. Then, give a split or something like that.

  • Tip, put it on the Chrome "window.Location" console and see what options you see. If any are worth it.

  • 1

    I’ll test it, thank you

  • 1

    in your specific case the solution will be window.location.search.substr(3) + window.location.hash

  • 1

    but I don’t consider it a good practice to do it the way I put it, and I agree with what Diego said about hashing the url.

  • in this case would be substr(4) to remove the = also, vlw @Karlzillner

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.