Home > Web Front-end > JS Tutorial > body text

How to convert js string and unicode code to each other? (code)

不言
Release: 2018-09-28 15:27:12
forward
7706 people have browsed it

本篇文章给大家带来的内容是关于js字符串与unicode码如何相互转换?(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

在我们的开发过程中,有时在对数据进行储存的时候,我们需要将字符串转成unicode。

比如,在jsp开发时,前端使用页面间传值时,将传值参数先存入cookie中,然后在使用的时候,再从ookie中取出。当存入cookie的参数为汉字或别的什么特殊字符时,就会导致服务器崩溃。

崩溃的大致原因:每次客户端与服务器之间的通信都会携带cookie,所以存入cookie的特殊字符就会被携带到服务器中。而在jsp开发的项目中,服务器在遇到cookie中这些特殊字符时,无法正确的解析,导致服务器崩溃。具体导致原因,后端会更加清楚,我也只是了解个大概,有兴趣的可以深入了解。

这时,我们在cookie存入的要是unicode码的话,就不会导致服务器崩溃的问题。当然也有别的处理方法,比如存入storage,让后端帮忙处理等。这里只说转码的解决方法。

方法中大致用到javascript中的两个自带的API。

fromCharCode():fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符。用法string.fromCharCode(unicode,16));

charCodeAt():charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。

看,javascript已经帮我们做完了很多事情。这两个API一次只能帮我们处理一个字符啊。还有就是这两个方法处理完和处理后都是 0 - 65535 之间的整数。而我们在使用的时候一般习惯性的在整数码之前加入\u,这个要手动的加入和删除。

代码如下:

//将unicode编码转字符串
var Unicode_Str=function(unicode){
    var result=[];
    var strArr=unicode.split('\\u');
    for(var i=0,len=strArr.length;i<len;i++){
        if(strArr[i]){
            result.push(string.fromCharCode(parseInt(strArr[i],16)))
        }
    }
    return result.join(&#39;&#39;);
}
//将字符串转unicode编码
var Str_Unicode=function(str){
    var unid=&#39;\\u&#39;;
    for(let i=0,len=str.length;i<len;i++){
        if(i<len-1){
            unid+=str.charCodeAt(i).toString(16)+&#39;\\u&#39;;
        }else if(i===len-1){
            unid+=str.charCodeAt(i).toString(16);
        }
    }
    return unid;
}
Copy after login

The above is the detailed content of How to convert js string and unicode code to each other? (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!