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

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

    To truly remove as much bloat as possible, consider not using a wrapper function at all:

    try {
        var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
    } catch (_) {
        // handle missing cookie
    }
    

    As long as you're familiar with RegEx, that code is reasonably clean and easy to read.

提交回复
热议问题