V
V
viktorulyushev2017-04-17 11:26:56
JavaScript
viktorulyushev, 2017-04-17 11:26:56

Execute a condition if a certain value is passed in the cookie?

On the site, I can change the city, and its value is stored in cookies, and the city itself is stored in this format
in a json file

{ "CityId": 781, "Name": "Санкт-Петербург", "RegionId": 58 },

I need to make a condition that if, for example, a CityId equal to 781 is passed in cookies, or something like that, then my code is executed. And can this be done in js?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pushkarev, 2017-04-17
@viktorulyushev

function getCookie(name) {
    function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); };

    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));

    return match ? match[1] : null;
};

var cities = [{ "CityId": 781, "Name": "Санкт-Петербург", "RegionId": 58 }],
    currentCity = cities.filter(function(data) {
        var currentCityId = getCookie('CityId');

        return data.CityId == currentCityId;
    });

console.log(currentCity);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question