在javascript中的字符到十六进制 [英] Char to Hex in javascript

查看:122
本文介绍了在javascript中的字符到十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以指导我如何在javascript中将字符转换为十六进制格式。


例如:


入力されたデータは范囲外です。


\\\入\\\力\\\さ\\\れ\\\た\\\デ\\\ー \\\タ\\\は\\\範\\\囲\\\外\\\で\\\す\\\。


此网站执行此操作



但我可以



谢谢你,Sarbbottam


<你可以循环遍历这些字符,并使用 charCodeAt 函数来获取他们的UTF-16值,然后构造



下面是我构建的代码比你链接的网站上的代码好多了,应该更容易理解:

  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 输出+ ='\\u'+ pad_four(input.charCodeAt(i).toString 16));
return output;
}

让我们细分一下。


  1. string_as_unicode_escape 接受一个参数,输入 / li>
  2. pad_four 是一个内部函数,它会用'0'字符填充字符串,直到长度至少为四个字符。

  3. $ c>
  4. $ b
  5. 对于字符串中的每个字符,请附加 \u 输出字符串。以 input.charCodeAt(i)取字符的UTF-16值,然后将其转换为十六进制字符串 .toString(16),然后用前导零填充,然后将结果附加到输出字符串。

  6. code>输出字符串。

正如Tim Down评论,我们还可以添加 0x10000 到 charCodeAt 值,然后 .slice(1)通过调用 .toString(16),实现填充效果。


Could anyone guide me on how to convert char to hex in javascript?

For example:

"入力されたデータは範囲外です。"
to
"\u5165\u529B\u3055\u308C\u305F\u30C7\u30FC\u30BF\u306F\u7BC4\u56F2\u5916\u3067\u3059\u3002"

This site does it

However I can not figure it out.

Any suggestion.

Thanks, Sarbbottam

解决方案

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;
}

Let's break it down.

  1. string_as_unicode_escape takes one argument, input, which is a string.
  2. 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.
  3. Start off by defining output as an empty string.
  4. For each character in the string, append \u to the output string. Take the UTF-16 value of the character with input.charCodeAt(i), then convert it to a hexadecimal string with .toString(16), then pad it with leading zeros, then append the result to the output string.
  5. Return the output string.

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中的字符到十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆