Catch only part of a url

1

Good afternoon! How can I get only a part of a current url? For example, let's say I have the following url:

link

I would like to get only the value that comes after ?ip= in this case dispensacao#15

Thank you

    
asked by anonymous 28.02.2018 / 18:05

5 answers

2

Use the Javascript split () function, like this:

<!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>
    
28.02.2018 / 18:49
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;
    }, { });
};

No 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)
    
28.02.2018 / 18:26
1

By default this javascript has this information in window.location and to get the value, you can use the URL class.

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

The value will be in the ip variable.

    
28.02.2018 / 18:41
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 getUrlVars () function, considering the url above, we will have the following return:

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

To get the value of the first parameter would look like this:

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

the second:

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

Source

    
28.02.2018 / 18:59
0

Try this, and the fence serves:

window.location.search
    
28.02.2018 / 18:39