前端特殊字符串的处理和页面之间传值

阅读更多
在客户输入信息时会有特殊符号,这个时候如果页面之间传值或页面之间的跳转时会有数据丢失的情况发。因为URL只能使用阿拉伯数字、英文字母[0-9a-zA-Z]可以不经过编码直接用于URL。如果URL中有汉字,就必须编码后使用,这是交给应用程序(浏览器)自己决定。这导致“URL编码”成为了一个混乱的领域。
现在主要使用两种编码方式encodeURIComponent()和encodeURI
两种的区别:
1.encodeURIComponent()只对URL中的部分进行,而不对整个URL编码。如北京市#和平区,encodeURIComponent(str),对“; / ? : @ & = + $ , #”进行编码,解码为decodeURIComponent()
2.encodeURI()是对整个URL编码,对应的解码是decodeURI()。特殊含义的符号“; / ? : @ & = + $ , #”,不进行编码,输出形式是utf-8。
而我的项目中出现的问题就是输入中有特殊符号使用encodeURIComponent()可以解决。
另外在设计页面之间传值的时候也要考虑Get和Post的设计,如果传值超过规定的长度,最好使用Post方式(这时要考虑真实场景中客户的使用方式)

当然主要的原因还是当前项目中使用了GBK的编码格式,所以定义编码格式的时候最好使用utf-8
所以使用GBK的时候要使用如下方法进行代码转换
function encodeUrlForGBK(str) {
    var regexs = new Array(
        new RegExp(',', 'g'),
        new RegExp('/','g'),
        new RegExp('\\?', 'g'),
        new RegExp(':', 'g'),
        new RegExp('@', 'g'),
        new RegExp('&', 'g'),
        new RegExp('=', 'g'),
        new RegExp('\\+', 'g'),
        new RegExp('\\$', 'g'),
        new RegExp('#', 'g')
    );
   
    var replaces = new Array('%2C', '%2F','%3F', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%23');
   
    for (var i = 0; i < regexs.length; i++) {
        str = str.replace(regexs[i], replaces[i]);
    }
    return str;
}

你可能感兴趣的:(前端特殊字符串的处理和页面之间传值)