簡體   English   中英

在javascript中將ascii轉換為十六進制

[英]Convert ascii to hex in javascript

我想將javascript僅將符號轉換為十六進制字符串。

所以,如果我有一個字符串:

http://www.mydomain.com

轉換結果為:

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

注意%而不是0x

您可以使用正則表達式:

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]表示“不是字母或數字的任何內容”( ^表示不在字符類開頭時)。

當傳遞要replace的函數時,它將調用該函數(以match作為參數),而不是用靜態字符串替換。

charCodeAt將獲取指定字符的字符代碼(通過參數),因此charCodeAt(0)將獲取第一個字符的字符代碼。

toString接受一個選項基本參數,該參數指定所需的基礎,並且基礎16是十六進制。

最后, (hex.length < 2 ? '0' + hex : hex)將在結果十六進制僅為一位的情況下添加前導零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM