简体   繁体   中英

Convert ascii to hex in javascript

I would like to convert a string into a hex with javascript just the symbols.

So if i have a string:

http://www.mydomain.com

the conversion result would be:

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

notice the % instead of the 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).

When passing a function to replace , it will call that function (with the match as an argument) instead of replacing with a static string.

charCodeAt will get the character code of a specified character (by the argument), so charCodeAt(0) gets the character code of the first character.

toString takes an option base argument specifying which base you want, and base 16 is hex.

And finally, (hex.length < 2 ? '0' + hex : hex) will add a leading zero in case the resulting hex is only one digit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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