gpt4 book ai didi

javascript - 检查字符串是否为 UTF-8 如果是则返回\u+hex 如果不​​是则返回 false

转载 作者:行者123 更新时间:2023-12-02 17:40:15 24 4
gpt4 key购买 nike

对于XSS safety ,我想将所有字符转换为\u+hex 编码。我见过UTF-16 solutions ,但我找不到 UTF-8 的任何内容。

我首先要确保所有字符都是UTF-8。在这里,我看到了很多解决方案,但没有一个与 JavaScript 一致。

如何测试字符串是否为 UTF-8,如果是则返回\u+hex 编码,否则返回 false?

最佳答案

function string_to_hex(input) {
var temp = 0, output = "";
for (var i = 0; i < input.length; i++) {
temp = input.charCodeAt(i);
if (temp > 0xFF) {
// if (temp == 192 || temp == 193 || temp > 244) {
return false;
}
output += "\\x" + temp.toString(16).slice(1); //lazy padding
}
return output;
}

如果您不检查非法代码点,则不需要注释掉该行。

关于javascript - 检查字符串是否为 UTF-8 如果是则返回\u+hex 如果不​​是则返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22274888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com