How to obtain url parameters in the address bar using javascript/jquery

Source: Internet
Author: User

Getting URLs using jquery and getting url parameters using jquery are common operations.

1. jquery is easy to get the url. The Code is as follows:
Copy codeThe Code is as follows:
Window. location. href;

In fact, it only uses the basic window object of javascript and does not use jquery knowledge.

2. It is complicated for jquery to obtain url parameters. Regular Expressions are needed, so it is important to learn javascript Regular Expressions well.

First, let's take a look at how javascript can be used to obtain a parameter in a url.
Copy codeThe Code is as follows:
Function getUrlParam (name)
{
Var reg = new RegExp ("(^ | &)" + name + "= ([^ &] *) (& | $ )"); // construct a regular expression object containing the target parameter
Var r = window. location. search. substr (1). match (reg); // match the target parameter
If (r! = Null) return unescape (r [2]); return null; // return the parameter value
}

Pass the parameter name in the url through this function to get the parameter value. For example, if the url is
Http://www.xxx.loc/admin/write-post.php? Cid = 79
To obtain the cid value, we can write it as follows:
Copy codeThe Code is as follows:
GetUrlParam ('cid ');

After understanding how javascript gets url parameters, we can use this method to expand a method for jquery to get url parameters through jquery.

Extension of the getUrlParam () method for jquery
Copy codeThe Code is as follows:
(Function ($ ){
$. GetUrlParam
= Function (name)
{
Var reg
= New RegExp ("(^ | &)" +
Name + "= ([^ &] *) (& | $ )");
Var r
= Window. location. search. substr (1). match (reg );
If (r! = Null) return unescape (r [2]); return null;
}
}) (JQuery );

After this method is extended for jquery, we can use the following method to obtain the value of a parameter.
Copy codeThe Code is as follows:
$. GetUrlParam ('cid ');

Related Article

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.