Method to get address bar parameters using JavaScript

  • 2020-05-07 19:15:31
  • OfStack


/**
 *  Gets the address bar parameter
 *
 * @example GetUrlString('id')
 *
 * @desc    Add judgment to the call to ensure that the program does not fail
 *             var myurl = GetUrlString('id');
 *             if (myurl != null && myurl.toString().length > 1) {
 *                  alert(GetUrlString("id")); 
 *             }
 *
 * @param String  param To get the parameter name in the address bar
 * @return String Value
 * @type String
 *
 * @name GetUrlString()
 *
 */
function GetUrlString(param) {
    var sValue = location.search.match(new RegExp("[\?\&]" + m + "=([^\&]*)(\&?)", "i"));
    return sValue ? decodeURI(sValue[1]) : decodeURI(sValue);
}

Call when 1 to make such a judgment, to avoid you do not pass parameters, such as your address is abc


window.onload = function() {   
    var myurl = GetParm("id");
    if (myurl != null && myurl.toString().length > 1) {
        alert(GetParm("id"));
    }
}

So you don't report an error!

Note: ECMAScript v3 has removed the unescape() function from the standard and objects to its use, so decodeURI() and decodeURIComponent() should be used instead.

Have you understood how to use JavaScript to get the address bar parameters? If in doubt, please leave a message.


Related articles: