JavaScript uses a regular fetch cookie

Source: Internet
Author: User

application uses regular expressions to get cookies


cookie = "id=123; Username=yang; id=123; Sex=1 "
If you want to get an ID now, how to write the regular expression.
The method of representing the value ([^;] *) Repeat any number of characters except the semicolon
The judgment of the end symbol (; |$)
var cookie = "id=123; Username=yang; Sex=1 ";
var reg4 =/(^|) Id= ([^;] *) (; |$)/;//a regular that matches a cookie
var arr = Cookie.match (REG4);//match method plays an array
Console.log (arr[2]);


Gets the Usernama corresponding value
var reg5 =/(^|) Username= ([^;] *) (; |$)/;//Gets the value of username
var arr2 = Cookie.match (REG5);
Console.log (ARR2); If the match method is not found, it returns null ["Username=yang;", "", "Yang", ";", Index:7, Input: "id=123; Username=yang; Sex=1 "]
Console.log (arr2[2]);//The second in the array is the value of the second group.


Gets the cookie corresponding to a cookie
function GetCookie (key) {
var str = "(^|)" + key + "= ([^;]) (;|$)";//[,,,]
var reg = new RegExp (str);
if (!arr)//arr array is null match did not find the cookie in the string
{
return null;
}
Return arr[2];//only need the value indexed in the array to be 2
}
Document.cookie = "Username=yang;";
Document.cookie = "id=123";


Alert (GetCookie ("color"));
Alert (GetCookie ("username"));

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.