javascript字符串如何进行编码转换


当前第2页 返回上一页

AJAX使用GET请求时传递中文字符串时也必须把中文字符串编码成unicode,一般会用到JS的自带函数escape().不过找到了更好的函数来确决中文字符转换成unicode编码的函数如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

function uniencode(text)

{

text = escape(text.toString()).replace(/+/g, "%2B");

var matches = text.match(/(%([0-9A-F]{2}))/gi);

if (matches)

{

for (var matchid = 0; matchid < matches.length; matchid++)

{

var code = matches[matchid].substring(1,3);

if (parseInt(code, 16) >= 128)

{

text = text.replace(matches[matchid], '%u00' + code);

}

}

}

text = text.replace('%25', '%u0025');

return text;

}

当然服务器端要对编码过的字符串进行第二次转码.把字符串转换成UTF-8编码.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

function convert_int_to_utf8($intval)

{

$intval = intval($intval);

switch ($intval)

{

// 1 byte, 7 bits

case 0:

return chr(0);

case ($intval & 0x7F):

return chr($intval);

// 2 bytes, 11 bits

case ($intval & 0x7FF):

return chr(0xC0 | (($intval >> 6) & 0x1F)) .

chr(0x80 | ($intval & 0x3F));

// 3 bytes, 16 bits

case ($intval & 0xFFFF):

return chr(0xE0 | (($intval >> 12) & 0x0F)) .

chr(0x80 | (($intval >> 6) & 0x3F)) .

chr (0x80 | ($intval & 0x3F));

// 4 bytes, 21 bits

case ($intval & 0x1FFFFF):

return chr(0xF0 | ($intval >> 18)) .

chr(0x80 | (($intval >> 12) & 0x3F)) .

chr(0x80 | (($intval >> 6) & 0x3F)) .

chr(0x80 | ($intval & 0x3F));

}

}

【推荐学习:javascript高级教程

以上就是javascript字符串如何进行编码转换的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

javascript怎么实现字符串转大写

学习用 javascript 实现归并排序

javascript怎么求数组最大最小值

javascript怎么删除数组元素

popper.js怎么下载

javascript实现电池状态的方法

详解javascript中的内存管理

javascript如何进行文档注释

javascript中this的用法是什么

generator函数与async函数的区别介绍

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...