3

I've got a javascript string called cookie and it looks like that:

__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en

It could have more ;xxxxxx; but always the entries will be surrounded by ;. Now i want to split my var into a array and search for the entry "language=xy", this entry should be saved in "newCookie".

Could anyone help me please i'm completly stucked at splitting the var into a array and search for the entry.

Thanks for helping and sharing

1
  • 1
    @user1109719 Java !== JavaScript. Commented Oct 9, 2012 at 6:19

2 Answers 2

3
var cookie = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;';

var cookie_array = cookie.split(';'); // Create an Array of all cookie values.

// cookie_array[0] = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10'
// cookie_array[1] = '__utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)'
// cookie_array[2] = '__utmb=43024181.19.10.1349761990'
// cookie_array[3] = '__utmc=43024181'
// cookie_array[4] = 'language=en'

var size = cookie_array.length; // Get Array size to prevent doing lookups in a loop.

for (var i = 0; i < size; i++) {
    var keyval = cookie_array[i].split('='); // Split into a key value array

    // What we're trying to find now.
    // keyval[0] = 'language'
    // keyval[1] = 'en'

    if (keyval[0] == 'language') { //keyval[0] is left of the '='
        //write new cookie value here
        console.log('Language is set to ' + keyval[1]);  // keyval[1] is right side of '='
    }
}

Hope this helps ya out.

For more info on the split() method look at split() Mozilla Developer Network (MDN) documentation

Sign up to request clarification or add additional context in comments.

2 Comments

Should be ; i < size and not ; i<= size
Thanks @Brombomb but last question is is var cookie now == language=en ? Or could you tell me how to set it ;)? Would be very nice i'm a completly javascript noob.
0

Use a simple regexp for this:

var getLanguage = function(cookie){
    var re = new RegExp(/language=([a-zA-Z]+);/);
    var m = re.exec(cookie);
    return m?m[1]:null;
};

var lang = getLanguage('__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;'); 
// lang = "en"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.