JS gets the specified URL parameter

Source: Internet
Author: User

In C #, PHP, JSP, there is a direct way to get the parameters specified in the URL, but Javascript does not have the present method, you have to write one yourself. In the Web development process, it is very common to get the parameters in the URL, so it is necessary to encapsulate it as a method that can be called directly. The following first describes the implementation process, and then share the code.

1, directly get the implementation of the parameters specified in the URL process

First through the document.location to obtain the current Web page URL, followed by the split method through the "? "Divide the Web site into two parts. If the URL has parameters (Arrobj.length > 1), then the Split method uses "&" to separate each parameter, and then uses the For loop to check if the parameter has the same parameters as the parameter to be found, and if so, returns the value of the parameter; Continue looping until all parameters are found. If there are no parameters in the URL and no parameters are found, NULL is returned.

2, the implementation code is as follows:

  Paraname wait for the name of the parameter
  function Geturlparam (paraname) {
    var url = document.location.toString ();
    var arrobj = Url.split ("?");

    if (Arrobj.length > 1) {
      var Arrpara = Arrobj[1].split ("&");
      var arr;

      for (var i = 0; i < arrpara.length; i++) {
arr = Arrpara[i].split ("=");

        if (arr! = null && arr[0] = = Paraname) {
          return arr[1];
}
}
      return "";
}
    else {
      return "";
}
}

 Call Method: Geturlparam ("id");

  To illustrate:

If the URL of the webpage has such a parameter test.htm?id=896&s=q&p=5, then call Geturlparam ("P"), return 5.

JS gets the specified URL parameter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.