pierrebalian
9/25/2017 - 5:42 PM

Get the value of a Cookie

Get the value of a Cookie

/**
 * Get the value of a cookie.
 * 
 * Example usage:
 * 		var gclid = getCookie( 'gclidCookie' );
 *
 * @param {string} cookieName The name of the cookie.
 *
 * @returns {string} The value of the cookie or empty string.
 */
function getCookie( cookieName ) {
	/**
     * The name of the cookie we are looking for, appended with an equals character
     * because cookies are actually strings of key=value pairs.
     *
     * @type {string}
     */
    var name = cookieName + '=';
    /**
     * Array of cookie key=value strings.
     *
     * document.cookie is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs).
     * We split that string into an array on the semicolon.
     *
     * @type {Array}
     */
    var cookieArray = document.cookie.split( ';' );
    /**
     * A loop counter.
     *
     * @type {number}
     */
    var counter = 0;
    /**
     * The current cookie string in the loop.
     *
     * @type {string}
     */
    var currentCookie = '';
    while ( counter < cookieArray.length ) {
        currentCookie = cookieArray[ counter ];
        while ( ' ' === currentCookie.charAt( 0 ) ) {
            currentCookie = currentCookie.substring( 1 );
        }
        if ( 0 === currentCookie.indexOf( name ) ) {
            return currentCookie.substring( name.length, currentCookie.length );
        }
        counter++;
    }
    /**
     * Cookie not found, empty, or mangled.
     */
    return '';
    
}