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

前端 未结 15 2186
猫巷女王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:37

    Here goes.. Cheers!

    function getCookie(n) {
        let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
        return a ? a[1] : '';
    }
    

    Note that I made use of ES6's template strings to compose the regex expression.

提交回复
热议问题