Escape and Decode Japanese Characters in JS

I tried to write a JavaScript method that escapes Japanese characters.

var esc_str=escape("γƒγƒ£γ‚€γƒŠγƒ’γƒγ‚€γƒ«β€’γƒͺγƒŸγƒ†γƒƒγƒ‰"); var dec_str=decodeURIComponent(esc_str); //%u30C1%u30E3%u30A4%u30CA%u30E2%u30D0%u30A4%u30EB%u2022%u30EA%u30DF%u30C6%u30C3%u30C9 is dec_str as per debugger- console log. console.log(dec_str); 

While decoding , I get the following error:

Uncaught URIError: URI malformed

How do we avoid Japanese characters in order to decode it correctly?

Any help is appreciated!

http://jsfiddle.net/hcU9C/

+4
source share
2 answers

The page you linked to says

Note. The escape () function should not be used to encode URIs. Use the encodeURI () function instead.

And it works:

 encodeURIComponent("γƒγƒ£γ‚€γƒŠγƒ’γƒγ‚€γƒ«β€’γƒͺγƒŸγƒ†γƒƒγƒ‰"); "%E3%83%81%E3%83%A3%E3%82%A4%E3%83%8A%E3%83%A2%E3%83%90%E3%82%A4%E3%83%AB%E2%80%A2%E3%83%AA%E3%83%9F%E3%83%86%E3%83%83%E3%83%89" decodeURIComponent("%E3%83%81%E3%83%A3%E3%82%A4%E3%83%8A%E3%83%A2%E3%83%90%E3%82%A4%E3%83%AB%E2%80%A2%E3%83%AA%E3%83%9F%E3%83%86%E3%83%83%E3%83%89") "γƒγƒ£γ‚€γƒŠγƒ’γƒγ‚€γƒ«β€’γƒͺγƒŸγƒ†γƒƒγƒ‰" 
+5
source

Ideally, you should use encodeURI or encodeURIComponent to encode strings and decodeURI or decodeURIComponent respectively to decode a string, since escape and unescape are deprecated.

If you want to use escape for encoding, use the unescape function instead of the decodeURIComponent function to decode the string.

From the MDN page,

The escape and unescape functions do not work properly for non-ASCII characters and are deprecated. In JavaScript 1.5 and later, use encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent.

The escape and unescape functions allow you to encode and decode strings. The escape function returns the hexadecimal encoding of the argument to the ISO Latin character set. The unescape function returns an ASCII string for the specified hexadecimal value.

+2
source

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


All Articles