我有一个名为“login”的 cookie,其中包含类似“username|hashcode|salt”的结构。
这是我的代码:
function readTheCookie(the_info)
{
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);
var broken_cookie2 = the_cookie.substr(6);
alert(broken_cookie2);
}
readTheCookie('login');
我给我
pickup22|d47f45d141bf4ecc999ec4c083e28cf7|4ece9bce292e1
现在我只想要第一部分(第一个管道之前的所有内容,在这种情况下,我想要pickup22)
我怎样才能做到这一点?因为用户名永远不会相同,所以我不能输入“固定”长度。
感谢任何帮助!
最佳答案
var readTheCookie = function (the_info) {
var the_cookie = document.cookie.split(";"), a = the_cookie.length, b;
for (b = 0; b < a; b += 1) {
if (the_cookie[b].substr(0, the_info.length) === the_info) {
return the_cookie.split("=")[1].split("|")[0];
}
}
if (b === a) {
return "";
}
},
username = readTheCookie('login');
这很好,很紧凑,而且易于阅读,最后它符合 JSLint 规范。享受吧!
关于javascript - 使用 substr 方法获取 cookie 值的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8262239/