How to use JS to get the value of a cookie

Source: Internet
Author: User

  1. How to use JS to get the value of a cookie

  2. Read all cookies belonging to the current document

  3. var allcookies = document. Cookie;

  4. Defines a function that is used to read a specific cookie value.

  5. function GetCookie (cookie_name)

  6. {   

  7. var allcookies = document. Cookie;

  8. var cookie_pos = allcookies. indexOf (Cookie_name); Length of index

  9. If an index is found, it represents the existence of a cookie,

  10. Conversely, the description does not exist.

  11. if (cookie_pos! =-1)

  12. {

  13. Put the Cookie_pos at the beginning of the value, just add 1 to the value.

  14. Cookie_pos + = cookie_name.length + 1; Here I have tried it, prone to problems, so please refer to the time yourself to study it well ...

  15. var cookie_end = allcookies. indexOf (";", Cookie_pos);

  16. if (cookie_end = =-1)

  17. {

  18. cookie_end = allcookies. length;   

  19. }

  20. var value = unescape(allcookies.substring (Cookie_pos, cookie_end));  Here you can get the value of the cookie you want ...

  21. }

  22. return value;

  23. }

  24. Calling functions

  25. var cookie_val = getcookie("username");


How to use JS to get the value of a cookie

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.