Labels

Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Wednesday, February 1, 2017

JavaScript: Get Values From URL Parameters


.
JavaScript: Get Values From URL Parameters

1) Create demo script on GitHub


<!-- browse http://notarazi.github.io/demo/plainjs/geturlparameters.html?uid=a&age=20 -->
<html>
<head>
<script type="text/javascript">
       function getParam(name)
       {
           name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
           var regexS = "[\\?&]"+name+"=([^&#]*)";
           var regex = new RegExp( regexS );
           var results = regex.exec(window.location.href);
           if(results == null)
               return "";
           else  
               return results[1];
       }
      function getUrlData()
      {
           var uid = getParam("uid");
           var age = getParam("age");
           document.write("uid:"+uid+"<br/>age:"+age);
      }
</script>
</head>
<body onload="getUrlData()">
</body>
</html>

2) Test



3) GitHub

Run: http://notarazi.github.io/demo/plainjs/geturlparameters.html?uid=a&age=20
Source: https://github.com/notarazi/notarazi.github.io/blob/master/demo/plainjs/geturlparameters.html
.

1 comment:

  1. Alternative codes to Regex manipulation,

    < script>
    var url = document.createElement('a');
    url.href = window.location.href;
    console.log(url.protocol); //(http:)
    console.log(url.hostname) ; //(www.example.com)
    console.log(url.pathname) ; //(/some/path)
    console.log(url.search) ; // (?name=value)
    console.log(url.hash); //(#anchor)
    < /script>

    ReplyDelete