简体   繁体   中英

get value after dash in Get Cookie in Javascript

Im getting the value of cookie,

Issue : in value after dash only that has to be printed, example below :

Key : agc

value : @MALLAPS-MCO

By trying out the below code im getting complete value " @MALLAPS-MCO " instead of only MCO

JS :

 function getCookie(name){
        var pattern = RegExp(name + "=.[^;]*")
        matched = document.cookie.match(pattern)
        if(matched){
            var cookie = matched[0].split('=')
            return cookie[1]
        }
        return false
    }

Appreciate for your help.

your split() with = only gets you till value "@MALLAPS-MCO" , you need to split() it again, as:

function getCookie(name){
    var pattern = RegExp(name + "=.[^;]*")
    matched = document.cookie.match(pattern)
    if(matched){
        var cookie = matched[0].split('=')
        //split "@MALLAPS-MCO" again using "-" as delimiter
        return cookie[1].split("-")[1];
    }
    return false
}

You can also solve this using just one regex:

function getCookie(name){
    var pattern = RegExp(name + "=.[^;]*")
    matched = document.cookie.match(pattern)
    if(matched){
        var pattern = ".*-(.*)"
        return matched[0].match(pattern)[1]; 
    }
    return false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM