Char to Hex in javascript(javascript中的字符到十六进制)
问题描述
谁能指导我如何在javascript中将char转换为十六进制?
例如:
Could anyone guide me on how to convert char to hex in javascript?
For example:
"入力されたデータは范囲外です."
到
"u5165u529Bu3055u308Cu305Fu30C7u30FCu30BFu306Fu7BC4u56F2u5916u3067u3059u3002"
"入力されたデータは範囲外です。"
to
"u5165u529Bu3055u308Cu305Fu30C7u30FCu30BFu306Fu7BC4u56F2u5916u3067u3059u3002"
这个网站做到了
但是我想不通.
任何建议.
谢谢,萨博坦
推荐答案
您可以遍历字符并使用 charCodeAt
函数获取它们的 UTF-16 值,然后用它们构造一个字符串.
You can loop through the characters and use the charCodeAt
function to get their UTF-16 values, then constructing a string with them.
这是我构建的一些代码,它比您链接的网站上的代码要好得多,并且应该更容易理解:
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;
}
让我们分解一下.
string_as_unicode_escape
采用一个参数,input
,它是一个字符串.pad_four
是一个做一件事的内部函数;它用前导'0'
字符填充字符串,直到长度至少为四个字符.- 首先将
output
定义为空字符串. - 对于字符串中的每个字符,将
u
附加到output
字符串.用input.charCodeAt(i)
取字符的 UTF-16 值,然后用.toString(16)
将其转换为十六进制字符串,然后用前导填充零,然后将结果附加到output
字符串. - 返回
输出
字符串.
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.
正如 Tim Down 所说,我们还可以将 0x10000
添加到 charCodeAt
值,然后添加 .slice(1)
调用产生的字符串.toString(16)
,实现填充效果.
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.
这篇关于javascript中的字符到十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:javascript中的字符到十六进制


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01