1.前台取到的cookie中的字符串是多个cookie的连接,例如这两种:var str = "OnlineCookie=OnlineCookie&UserType=11111111111111111&UID=39&UserName=张三; UID=; UserType=; UserName="; var str2 = "OnlineCookie=OnlineCookie&UserType=11111111111111111&UID=39&UserName=%e5%bc%a0%e4%bf%8a; UID=; UserType=; UserName=; UserCookie=ZZSAPP&UnitName=北京"2.我需要获取的是指定名字后的cookie的值,例如:getCookie(str,"OnlineCookie","UserType"); // 返回 11111111111111111getCookie(str,"OnlineCookie","UserName"); // 返回 "张三"getCookie(str2,"ZSAPP","UnitName"); //返回 "北京"3.我原来是使用数组的方式来写。可是感觉好复杂,所以想换成正则的方式来做function getCookie(str,userCookieName,name) { var cookie = str; if (cookie) { var temp = cookie.split(';'); for (var k = 0, max = temp.length; k < max; k++) { if (temp[k].indexOf(userCookieName) > -1) { var arr = temp[k].split('&'); for (var i = 0; i < arr.length; i++) { var arr1 = arr[i].split('='); for (var j = 0; j < arr1.length; j++) { if (arr1[0] == name) { return arr1[1]; break; } } } } } } return '';}3.这个函数怎么用Js的正则表达式书写呢?function getCookie(str,userCookieName,name){}
3 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
function getCookieValue(key, cookieStr) {
var result = new RegExp(`(?:^|\s)${key}=([^;]*)`).exec(cookieStr)
return result && result[1]
}
宝慕林4294392
TA贡献2021条经验 获得超8个赞
function getCookie(str,userCookieName,name){
var regex=new RegExp('\\b'+userCookieName+'\\b.*?&'+name+'=([^&;]*)','g');
var result=regex.exec(str);
return result&&result[1];
}
添加回答
举报
0/150
提交
取消