Avoid non-ASCII characters in JavaScript

Is there any function to do the following?

var specialStr = 'ipsum áá éé lore'; var encodedStr = someFunction(specialStr); // then encodedStr should be like 'ipsum \u00E1\u00E1 \u00E9\u00E9 lore' 

I need to encode characters that are not in the ASCII range, and I need to do this with this encoding. I do not know his name. Perhaps this is unicode?

+4
source share
4 answers

This should do the trick:

 function padWithLeadingZeros(string) { return new Array(5 - string.length).join("0") + string; } function unicodeCharEscape(charCode) { return "\\u" + padWithLeadingZeros(charCode.toString(16)); } function unicodeEscape(string) { return string.split("") .map(function (char) { var charCode = char.charCodeAt(0); return charCode > 127 ? unicodeCharEscape(charCode) : char; }) .join(""); } 

For instance:

 var specialStr = 'ipsum áá éé lore'; var encodedStr = unicodeEscape(specialStr); assert.equal("ipsum \\u00e1\\u00e1 \\u00e9\\u00e9 lore", encodedStr); 
+12
source

Just for information, you can do, as Domenik said, or use the escape function, but this will lead to the creation of Unicode with a different format (more browser friendly):

 >>> escape("áéíóú"); "%E1%E9%ED%F3%FA" 
+1
source

If you need a hexadecimal encoding, not Unicode, then you can simplify @Domenic's answer to:

 "aäßåfu".replace(/./g, function(c){return c.charCodeAt(0)<128?c:"\\x"+c.charCodeAt(0).toString(16)}) returns: "a\xe4\xdf\xe5fu" 
0
source

This works for me. In particular, when using the Dropbox REST API:

  encodeNonAsciiCharacters(value: string) { let out = "" for (let i = 0; i < value.length; i++) { const ch = value.charAt(i); let chn = ch.charCodeAt(0); if (chn <= 127) out += ch; else { let hex = chn.toString(16); if (hex.length < 4) hex = "000".substring(hex.length - 1) + hex; out += "\\u" + hex; } } return out; } 
0
source

All Articles