简体   繁体   English

需要在JavaScript中转义非ASCII字符

[英]Need to escape 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 the characters that are out of ASCII range, and need to do it with that encoding. 我需要编码超出ASCII范围的字符,并需要使用该编码。 I don't know its name. 我不知道它的名字。 Is it Unicode maybe? 它可能是Unicode吗?

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 example: 例如:

var specialStr = 'ipsum áá éé lore';
var encodedStr = unicodeEscape(specialStr);

assert.equal("ipsum \\u00e1\\u00e1 \\u00e9\\u00e9 lore", encodedStr);

Just for information you can do as Domenic said or use the escape function but that will generate unicode with a different format (more browser friendly): 只是为了获取您可以做的信息,如Domenic所说或使用escape函数,但这将生成具有不同格式的unicode(更适​​合浏览器):

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

If you need hex encoding rather than unicode then you can simplify @Domenic's answer to: 如果您需要十六进制编码而不是unicode,那么您可以简化@ Domenic的答案:

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

returns: "a\xe4\xdf\xe5fu"

This works for me. 这适合我。 Specifically when using the Dropbox REST API: 特别是在使用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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM