I'm helping a nonprofit design a trilingual website: English, French, and Haitian Creole. I've been able to set, change, and delete cookies for the visitors' language choice -- that part isn't the problem.
The problem is that the only way I've found to READ the cookie value uses regex. I suppose I don't have a problem with regex, per se, but I really just don't understand it...at all! I copied and pasted some code that does work, but if something ever happens that breaks it or it otherwise malfunctions, I know I won't be able to troubleshoot it or fix it. Can anyone suggest a way to use jQuery or just plain Javascript to read one value inside a cookie?
The cookie sets the following:
document.cookie = "language=EN"
(or FR, or HT, depending on the visitor's choice) It sets both max-age
AND expires
for cross-browser compatibility, and its path is set to /
so it covers the whole site. This part isn't the problem.
To read it, I use the following code, which DOES work:
var lang = document.cookie.replace(/.*\blanguage=(\w+)\b.*/, "$1");
if (lang == "EN") { window.location = "http://example.com/en"; } else
if (lang == "FR") { window.location = "http://example.com/fr"; } else
if (lang == "HT") { window.location = "http://example.com/ht"; };
However, this is the part that I really don't understand. All that regex coding, and the fact that I'm using .replace()
, makes no sense to me. I've played around with using .indexOf()
and .toString()
to read the cookie with search
or other functions, but nothing seems to work.
I'm using HTML5 with jQuery 3.1.0 (not php), but like I said, I'm fine with just plain Javascript to send returning visitors to their language's home page.
I'm just trying to preserve my ability to troubleshoot in the future. Thank you for any help you can provide.
EDIT: Added solution below based on @roberto06's suggestion.