0

Is it possible to detect with jquery a value from the current url?

For example:

http://example.com/home.php?name=john

From this url I need to know if name == john:

  $(document).ready(function() {
      if (window.location.name == john)
        alert("my name is john");
    });
peace_love
  • 6,229
  • 11
  • 69
  • 157

2 Answers2

1

You can try to use indexOf() in string to find the string you are checking for.

$(document).ready(function() {
    if (location.search.indexOf('name=john') !== -1)
        alert("my name is john");
});

This way is very basic, does not cover all the possibilities.

If you really want to get the URL variable, then use

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

and check by getParameterByName('name') == 'john'.

rrk
  • 15,677
  • 4
  • 29
  • 45
1

Try this

function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}​

And this is how you can use this function assuming the URL is

http://dummy.com/?technology=jquery&blog=jquerybyexample

var tech = GetQueryStringParams('technology');
var blog = GetQueryStringParams('blog');

Courtsey

Gagan Jaura
  • 710
  • 1
  • 5
  • 14