Developer
Developer

Reputation: 1437

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.

Upvotes: 0

Views: 368

Answers (2)

k-nut
k-nut

Reputation: 3595

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
}

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

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
}

Upvotes: 2

Related Questions