2

I am learning how to do a query string what html would you use for the following function on the sending and receiving page to see the result of author?

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

I found it at: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx

Are they any good query string examples?

Jack Billy
  • 7,141
  • 6
  • 27
  • 38
phil
  • 21
  • 1
  • 2
  • On a side note you do know about `window.location.search` do you? See: http://stackoverflow.com/a/7090123/797194 – m90 Dec 25 '12 at 16:31
  • possible duplicate of http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript (i know this is coming late, but it's worth noting - this seems to be a super common question) – mr rogers Feb 19 '14 at 09:54

3 Answers3

0

I can't quite tell what you are asking but I guess you're looking for a way to test this method and verify its behavior. Here is what I would do, save these contents in an HTML file:

<html>
  <body>
    <form name="form1">
      Key: <input type="text" name="text1" value="author"/>
      <input type="button" name="button1" value="Test"/>
    </form>
    <script>
      document.form1.button1.onclick = function() {
        alert(getQuerystring(document.form1.text1.value));
      }
      function getQuerystring(key, default_) {
        // your code here...
      }
    </script>
  </body>
</html>

Now you can open your HTML page in a web browser and add a query string like "?author=me&foo=bar". For example, if your file is saved in "C:\tmp\example.html" then your URL should look like this:

file:///c:/tmp/example.html?author=me&foo=bar

The page will show a text field (which says "author" by default) and a button and when you press the button the page will show a popup with the result of running the function with the value you put in the text field. With my example query string, the key "author" should alert "me" and the key "foo" should alert "bar".

maerics
  • 151,642
  • 46
  • 269
  • 291
-1
function getQuerystringParameter(name, _default) {
    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);
    return (match && decodeURIComponent(match[1].replace(/\+/g, ' ')) || _default;
}
Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
-1

http://www.example.com?variable=string&var2=ok&var3=str3

is an example of a query string

<script>
var_this = getQuerystring(var2);
if(var_this == "ok"){
  //do this
}else{
  // do this
}
</script>
Derek
  • 4,864
  • 5
  • 28
  • 38