简体   繁体   English

在javascript中将ascii转换为十六进制

[英]Convert ascii to hex in javascript

I would like to convert a string into a hex with javascript just the symbols. 我想将javascript仅将符号转换为十六进制字符串。

So if i have a string: 所以,如果我有一个字符串:

http://www.mydomain.com http://www.mydomain.com

the conversion result would be: 转换结果为:

http%3A%2F%2Fwww%2Emydomain%2Ecom http%3A%2F%2Fwww%2Emydomain%2Ecom

notice the % instead of the 0x 注意%而不是0x

You could use regex: 您可以使用正则表达式:

var url = 'http://example.com';
var escaped = url.replace(/[^A-Za-z0-9]/g, function(match) {
    var hex = match.charCodeAt(0).toString(16);
    return '%' + (hex.length < 2 ? '0' + hex : hex);
});
console.log(escaped); // => "http%3a%2f%2fexample%2ecom"

[^A-Za-z0-9] means "anything that's NOT a letter or number" ( ^ means not when placed at the beginning of a character class). [^A-Za-z0-9]表示“不是字母或数字的任何内容”( ^表示不在字符类开头时)。

When passing a function to replace , it will call that function (with the match as an argument) instead of replacing with a static string. 当传递要replace的函数时,它将调用该函数(以match作为参数),而不是用静态字符串替换。

charCodeAt will get the character code of a specified character (by the argument), so charCodeAt(0) gets the character code of the first character. charCodeAt将获取指定字符的字符代码(通过参数),因此charCodeAt(0)将获取第一个字符的字符代码。

toString takes an option base argument specifying which base you want, and base 16 is hex. toString接受一个选项基本参数,该参数指定所需的基础,并且基础16是十六进制。

And finally, (hex.length < 2 ? '0' + hex : hex) will add a leading zero in case the resulting hex is only one digit. 最后, (hex.length < 2 ? '0' + hex : hex)将在结果十六进制仅为一位的情况下添加前导零。

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

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