javascript 在javascript中将字符转换为十六进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5786483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Char to Hex in javascript
提问by user626818
Could anyone guide me on how to convert char to hex in javascript?
For example:
谁能指导我如何在 javascript 中将 char 转换为十六进制?
例如:
"入力されたデータは範囲外です。"
to
"\u5165\u529B\u3055\u308C\u305F\u30C7\u30FC\u30BF\u306F\u7BC4\u56F2\u5916\u3067\u3059\u3002"
“入力されたデータは范囲外です。”
到
“\u5165\u529B\u3055\u308C\u305F\u30C7\u30FC\u30BF\u306F\u7BC4\u306F\u7BC4\u3061\u3061”
However I can not figure it out.
但是我想不通。
Any suggestion.
任何建议。
Thanks, Sarbbottam
谢谢,萨博坦
回答by Delan Azabani
You can loop through the characters and use the charCodeAt
function to get their UTF-16 values, then constructing a string with them.
您可以遍历字符并使用该charCodeAt
函数获取它们的 UTF-16 值,然后用它们构造一个字符串。
Here's some code I constructed that is much better than the code on the site you've linked, and should be easier to understand:
这是我构建的一些代码,它比您链接的站点上的代码要好得多,并且应该更容易理解:
function string_as_unicode_escape(input) {
function pad_four(input) {
var l = input.length;
if (l == 0) return '0000';
if (l == 1) return '000' + input;
if (l == 2) return '00' + input;
if (l == 3) return '0' + input;
return input;
}
var output = '';
for (var i = 0, l = input.length; i < l; i++)
output += '\u' + pad_four(input.charCodeAt(i).toString(16));
return output;
}
Let's break it down.
让我们分解一下。
string_as_unicode_escape
takes one argument,input
, which is a string.pad_four
is an internal function that does one thing; it pads strings with leading'0'
characters until the length is at least four characters long.- Start off by defining
output
as an empty string. - For each character in the string, append
\u
to theoutput
string. Take the UTF-16 value of the character withinput.charCodeAt(i)
, then convert it to a hexadecimal string with.toString(16)
, then pad it with leading zeros, then append the result to theoutput
string. - Return the
output
string.
string_as_unicode_escape
接受一个参数,input
,它是一个字符串。pad_four
是一个做一件事的内部函数;它用前导'0'
字符填充字符串,直到长度至少为四个字符。- 首先定义
output
为空字符串。 - 对于字符串中的每个字符,附加
\u
到output
字符串。用 取字符的 UTF-16 值input.charCodeAt(i)
,然后用 将其转换为十六进制字符串.toString(16)
,然后用前导零填充它,然后将结果附加到output
字符串中。 - 返回
output
字符串。
As Tim Down commented, we can also add 0x10000
to the charCodeAt
value and then .slice(1)
the string resulting from calling .toString(16)
, to achieve the padding effect.
作为添下的评论中,我们还可以添加0x10000
到charCodeAt
值,然后.slice(1)
从调用产生的字符串.toString(16)
,来达到填充的效果。
回答by Drew
function string_as_unicode_escape(str){
return str.split("").map(function(s){
return "\u"+("0000" + s.charCodeAt(0).toString(16)).slice(-4);
}).join("");
}
回答by Hashbrown
You can just use ordinary replace()
for this.
您可以replace()
为此使用普通。
'! \u0100 力 '.replace(
/[^\x00-\xFF]/g,
function(ch) {
return ('\u0' + ch.charCodeAt(0).toString(16))
.replace(/0(?=....$)/, '');
}
)
Produces ! \u0100 \u529b \ud83d\ude03
生产 ! \u0100 \u529b \ud83d\ude03
Incredibly succinct, and handles the padding issue without cumbersome if
s or slow slice()
s.
Works in all browsersunlike map()
.
Note how it only replaces the characters you need to (!
and were untouched) without cumbersome iteration or slow
split()
ing.
Just as with the other answers, it also correctly handles surrogate pairs (turned into the two bytes
\ud83d\ude03
).
令人难以置信的简洁,并且无需繁琐的if
s 或缓慢的slice()
s即可处理填充问题。
工程在所有浏览器不同map()
。
请注意它如何仅替换您需要(!
并且未触及)的字符,而无需繁琐的迭代或缓慢的
split()
ing。
就像其他答案一样,它也可以正确处理代理对(变成两个字节
\ud83d\ude03
)。
Putting it in its own function and keeping the two regexes static would make it even faster again too if you're planning on reusing the function many times.
如果您计划多次重用该函数,将它放在自己的函数中并保持两个正则表达式静态也会使其更快。
You can do all characters if you really need to by changing [^\x00-\xFF]
to .
, \\u0
to \\u000
, and /0(
to /0+(
.
你可以做所有的字符,如果你真的改变需要[^\x00-\xFF]
到.
,\\u0
到\\u000
和/0(
到/0+(
。
回答by Juan
var hex=new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
var hex=new Array('0','1','2','3','4','5','6','7','8','9','a', 'b','c','d','e','f');
function stringEncode()
{
var x=document.getElementById("from_text");
var preescape="" + x.value;
var escaped="";
var i=0;
for(i=0;i<preescape.length;i++)
{
escaped=escaped+encodeChar(preescape.charAt(i));
}
//x=document.getElementById("to_text");
x.value=escaped;
//alert("Codigo: "+escapeHtml(escaped));
//document.getElementById('string_example').innerHTML="<b>String example with text</b><br/><br/>String s=\""+escapeHtml(escaped)+"\";<br/><br/>";
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function encodeChar(original)
{
var found=true;
var thecharchar=original.charAt(0);
var thechar=original.charCodeAt(0);
switch(thecharchar) {
case '\n': return "\n"; break; //newline
case '\r': return "\r"; break; //Carriage return
case '\'': return "\'"; break;
case '"': return "\\""; break;
case '\': return "\\"; break;
case '\t': return "\t"; break;
case '\b': return "\b"; break;
case '\f': return "\f"; break;
default:
found=false;
break;
}
if(!found)
{
if(thechar>127) {
var c=thechar;
var a4=c%16;
c=Math.floor(c/16);
var a3=c%16;
c=Math.floor(c/16);
var a2=c%16;
c=Math.floor(c/16);
var a1=c%16;
// alert(a1);
return "\u"+hex[a1]+hex[a2]+hex[a3]+hex[a4]+"";
}
else
{
return original;
}
}
}
//------------------------ lo llamarias con
//------------------------ lo lamarias con