JS 富文本编码、解码


第一种 

escape()unescape()方法

escape() 方法能够把 ASCII之外的所有字符转换为 %xx 或 %uxxxx(x表示十六进制的数字)的转义序列。从 \u000 到 \u00ff 的 Unicode 字符由转义序列 %xx 替代,其他所有 Unicode 字符由 %uxxxx 序列替代。

 如

var str = "编程最美";
console.log(escape(str));//返回"%u7F16%u7A0B%u6700%u7F8E"

与 escape() 方法对应,unescape() 方法能够对 escape() 编码的字符串进行解码。

unescape("%u7F16%u7A0B%u6700%u7F8E");//返回"编程最美"

如果前台展示时不想解码,可以在后台接收到escape() 方法处理的数据时可以用System.Web.HttpUtility.UrlDecode(str)处理下,获取到的就是编码前的数据了

 

第二种

// 转为unicode 编码  
function encodeUnicode(str) {
    var res = [];
    for (var i = 0; i < str.length; i++) {
        res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    }
    return "\\u" + res.join("\\u");
}

// 解码  
function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    //转换中文
    str = unescape(str);
    //将其他受影响的转换回原来
    str = str.replace(/%/g, "\\");
    //对网址的链接进行处理
    str = str.replace(/\\/g, "");
    return str;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM