What is the shortest function for reading a cookie by name in JavaScript?

前端 未结 15 1946
猫巷女王i
猫巷女王i 2020-11-22 17:17

What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scri

15条回答
  •  忘了有多久
    2020-11-22 17:35

    To have all cookies accessible by name in a Map:

    const cookies = "a=b ; c = d ;e=";
    const map = cookies.split(";").map((s) => s.split("=").map((s) => s.trim())).reduce((m, [k, v]) => (m.set(k, v), m), new Map());
    console.log(map); //Map(3) {'a' => 'b', 'c' => 'd', 'e' => ''}
    map.get("a"); //returns "b"
    map.get("c"); //returns "d"
    map.get("e"); //returns ""
    

提交回复
热议问题