javascript 中文轉(zhuǎn)unicode
在編寫JavaScript代碼的過程中,有時(shí)我們需要將中文字符轉(zhuǎn)換成unicode格式。這種轉(zhuǎn)換的原因很多,比如在URL鏈接中需要將中文轉(zhuǎn)換成%u的形式傳遞,或者在處理JSON數(shù)據(jù)時(shí)需要將中文轉(zhuǎn)換成\u的形式。
JavaScript提供了多種方法將中文轉(zhuǎn)換成unicode格式。下面就來逐一介紹這些方法。
1.使用escape()方法
escape()方法是將字符串轉(zhuǎn)換成十六進(jìn)制的unicode編碼,每個(gè)中文字符會被轉(zhuǎn)換成6個(gè)十六進(jìn)制字符表示。例如,中文字符“你”會被轉(zhuǎn)換成“%u4F60”。
示例代碼如下:
let str = "你好";
let unicodeStr = escape(str);
console.log(unicodeStr); // 輸出:%u4F60%u597D
2.使用encodeURI()方法
encodeURI()方法是對URL中的中文字符進(jìn)行轉(zhuǎn)義,將它們轉(zhuǎn)換成%u-encoded hexadecimal形式進(jìn)行傳輸。這個(gè)方法不僅可以將中文字符轉(zhuǎn)換成unicode格式,還可以將其他特殊字符進(jìn)行轉(zhuǎn)義。
示例代碼如下:
let str = "你好";
let unicodeStr = encodeURI(str);
console.log(unicodeStr); // 輸出:%E4%BD%A0%E5%A5%BD
3.使用encodeURIComponent()方法
encodeURIComponent()方法需要將參數(shù)作為字符串傳入函數(shù),它會對字符串中的所有非字母數(shù)字字符進(jìn)行轉(zhuǎn)義,包括中文字符。將中文字符轉(zhuǎn)換成unicode格式。
示例代碼如下:
let str = "你好";
let unicodeStr = encodeURIComponent(str);
console.log(unicodeStr); // 輸出:%E4%BD%A0%E5%A5%BD