简体   繁体   中英

Javascript - How to display only the value of a cookie?

I have searched several places trying to find out how to do display only the value of a cookie rather than the whole key but they all seemed needlessly complex for what I'm doing. I've got a single cookie with only one key, userName = something, and I can't figure out how to display only the "something" rather than userName = something.

function userCookie(form)
{
    if(form.User_Name.value == "")
    {
        alert("Cannot accept a blank user name, please enter a valid name");
        return false;
    }
    else
    {
        document.cookie="userName=" + form.User_Name.value;
        alert(document.cookie);
        return false;
    }                       
}

function newWindow() 
{       
    var userWindow = window.open("","MyUserName","height=300,width=300");
    userWindow.document.open();
    userWindow.document.write("<p>Welcome Back</p>");
    userWindow.document.write(document.cookie);
    userWindow.document.close();
}

document.cookie will always return key,value pair like cookie1=value1;cookie2=value2 . You can use the following function to split the cookieName and "=" from the document.cookie to get the value.

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

The code is from w3schools .

如果您始终只有一个cookie,那么document.cookie.split("=")[1]就足够简单了。

var cookieArray = document.cookie.split("; "),
    cookieObject = {},
    i, pair;

for (i = cookieArray.length - 1; i >= 0; i--) {
    pair = cookieArray[i].split("=");
    cookieObject[pair[0]] = pair[1];
}

alert(cookieObject.userName);
function getCookie(name) {
  let x = document.cookie.split(";").find(a => a.includes(name + "="));
  return !!x ? x.trim().substr(name.length+1) : ""
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM