What is the "best" way to get and set a single cookie value using JavaScript


The “best” way to get and set a single cookie value using JavaScript depends on your specific needs and preferences, but here’s a basic example of how you can achieve this:

To set a cookie value:

document.cookie = "cookieName=cookieValue";

To get a cookie value:

var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)cookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1");

In the above example, to set a cookie value, you simply assign the value to document.cookie, which creates a new cookie or updates an existing one with the same name.

To get a cookie value, you need to extract the value from the cookie string returned by document.cookie. The regular expression /^(?:.;)?\scookieName\s*=\s*([^;]+)(?:.*)?$/ can be used to extract the value of the cookie with name “cookieName”. Here, the regex is first matched with the string of the entire cookie, and then the group that matches the value of the cookie is captured.

Note that if you have multiple cookies with the same name, this method will only return the value of the first matching cookie. In such cases, you may need to write a more complex function to parse the cookie string and return the desired value. Additionally, you may want to set additional options like an expiration date or a path for the cookie.