用正则实现根据name获取cookie中的值

通过正则表达式解析document.cookie字符串,实现根据cookie名称获取对应值的方法

问题

在前端开发中,我们经常需要读取cookie中的值。document.cookie 返回的是一个字符串,格式类似 "name1=value1; name2=value2; name3=value3"。我们需要实现一个方法,通过cookie的name来获取对应的value值。

解答

/**
 * 根据name获取cookie中的值
 * @param {string} name - cookie的名称
 * @returns {string|null} 返回对应的cookie值,不存在则返回null
 */
function getCookie(name) {
  // 构建正则表达式:匹配 name=value 的模式
  // (^|;\s*) 表示开头或分号+可选空格
  // ([^;]*) 表示捕获非分号的任意字符(cookie的值)
  const reg = new RegExp('(^|;\\s*)' + name + '=([^;]*)');
  
  // 在document.cookie中执行正则匹配
  const match = document.cookie.match(reg);
  
  // 如果匹配成功,返回解码后的值(索引2是第二个捕获组)
  // 如果匹配失败,返回null
  return match ? decodeURIComponent(match[2]) : null;
}

更简洁的写法:

function getCookie(name) {
  const match = document.cookie.match(new RegExp('(^|;\\s*)' + name + '=([^;]*)'));
  return match ? decodeURIComponent(match[2]) : null;
}

处理特殊字符的安全版本:

function getCookie(name) {
  // 对name进行转义,防止特殊字符影响正则匹配
  const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const reg = new RegExp('(^|;\\s*)' + escapedName + '=([^;]*)');
  const match = document.cookie.match(reg);
  return match ? decodeURIComponent(match[2]) : null;
}

使用示例

// 假设当前cookie为: "username=zhangsan; token=abc123; age=25"

// 获取username
const username = getCookie('username');
console.log(username); // 输出: "zhangsan"

// 获取token
const token = getCookie('token');
console.log(token); // 输出: "abc123"

// 获取不存在的cookie
const email = getCookie('email');
console.log(email); // 输出: null

// 处理包含中文的cookie(假设cookie为: "city=%E5%8C%97%E4%BA%AC")
const city = getCookie('city');
console.log(city); // 输出: "北京" (自动解码)

完整的cookie操作示例:

// 设置cookie
function setCookie(name, value, days = 7) {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = `${name}=${encodeURIComponent(value)};expires=${date.toUTCString()};path=/`;
}

// 删除cookie
function removeCookie(name) {
  setCookie(name, '', -1);
}

// 使用示例
setCookie('username', '张三');
console.log(getCookie('username')); // "张三"

removeCookie('username');
console.log(getCookie('username')); // null

关键点

  • 正则表达式构成(^|;\\s*) 匹配字符串开头或分号+空格,确保精确匹配cookie名称
  • 捕获组使用([^;]*) 捕获cookie的值部分,[^;] 表示匹配除分号外的任意字符
  • URL解码:使用 decodeURIComponent() 解码cookie值,因为cookie存储时通常会进行URL编码
  • 边界处理:通过 (^|;\\s*) 避免匹配到名称相似的cookie(如name和username)
  • 特殊字符转义:如果cookie名称包含正则特殊字符,需要先转义再构建正则表达式
  • 返回值处理:匹配失败时返回null而不是undefined,语义更明确
  • 兼容性document.cookie 和正则表达式都有良好的浏览器兼容性