How to save other languages ​​(unicode) in cookies and return them back

Can someone help me understand how to save a cookie value that is in another language, and how to restore it again in that language.

It seems that my cookies in a foreign language turn into garbage when it is removed after being saved.

Some codes:

Write the cookie code:

function writecook() { document.cookie = "lboxcook=" + document.getElementsByTagName('input')[0].value; //input[0] is the input box who value is stored } 

Get cookie code:

  <script language="JavaScript"> function get_cookie ( cookie_name ) { var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' ); if ( results ) return ( unescape ( results[2] ) ); else return null; } </script> 

Thanks.

+4
source share
1 answer

Use encodeURIComponent() when setting the cookie and decodeURIComponent() when retrieving it.

 var cookieValue = document.getElementsByTagName('input')[0].value; document.cookie = "lboxcook=" + encodeURIComponent(cookieValue); function get_cookie(cookie_name) { var results = document.cookie.match ('(^|;) ?' + cookie_name + '=([^;]*)(;|$)'); return results ? decodeURIComponent(results[2]) : null; } 
+15
source

Source: https://habr.com/ru/post/1213355/


All Articles