使用substr方法获取cookie值的一部分



我有一个名为"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 | 4 ece9bce292e1

现在我只想要第一部分(第一个管道之前的所有内容,在这种情况下,我想要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兼容。享受吧!

最好的方法是使用split()方法。

var parts = new Array();
parts = broken_cookie2.split("|");
var username = parts[0];
var hashcode = parts[1];
var salt = parts[2];

最新更新