简体   繁体   中英

What is the easiest way to read a single variable in a URL?

Using the Tumblr API, I'm constructing anchors to my posts using their ID numbers, with the idea that if I can read the variable from the URL, I can use another script to find a single post using that ID and construct it on my website, keeping my viewers on my page instead of leaving to go to Tumblr. What would be the easiest way to do that?

Here's what the URL would be as an example:

    nevermorestudiosonline.com/singlepost.php?id=123456789

Plain and simple, I want to read the ID number from the URL and store it to a variable to be used by the API call to get the post. I just don't know how to get the ID from URL to variable.

You can use querystring module to extract id from the URL.

var querystring = require('querystring');
var url = "nevermorestudiosonline.com/singlepost.php?id=123456789"

var id = querystring.parse(url)["id"];

JavaScript Way

var url = 'nevermorestudiosonline.com/singlepost.php?id=123456789';
var temp = url.split('=');
var id = temp[1];

// Now you can play with this id and use it the way you
// you want.
console.log(id);`
var url = "nevermorestudiosonline.com/singlepost.php?id=123456789";
    url = url.split("?")[1]; 
    url = url.slice(url.indexOf("id=") + 3,url.length)      
    console.log(url);

You can access location.search , which will give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.

The code you can use this:

<script type="text/javascript"> 
    var QueryString = function () {
      // This function is anonymous, is executed immediately and 
      // the return value is assigned to QueryString!
      var query_string = {};
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
            // If first entry with this name
        if (typeof query_string[pair[0]] === "undefined") {
          query_string[pair[0]] = decodeURIComponent(pair[1]);
            // If second entry with this name
        } else if (typeof query_string[pair[0]] === "string") {
          var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
          query_string[pair[0]] = arr;
            // If third or later entry with this name
        } else {
          query_string[pair[0]].push(decodeURIComponent(pair[1]));
        }
      } 
        return query_string;
    }();    
    console.log(QueryString);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM