开发常用tool

开发常用工具

(1) 获取url参数
(2)判断是否是PC端
(3)写入cookie
(4)读取cookie
(5)处理字符串中的转义字符,将反斜杠\替换为转义符\
(6)处理字符串中的转义符,将<>替换为<>

1.获取url参数

    function getUrlArgument(name){
        var search=location.search.split('?')[1]||'';
        var arr=search.split('&');
        for(var i in arr){
            var res = '';
            var cArr = arr[i].split('=');
            if(cArr.length > 2) {
                res = arr[i].slice(arr[i].indexOf('=') + 1);
            } else {
                res = cArr[1];
            }
            if(cArr[0]==name) return decodeURIComponent(res);
        }
        return '';
    },
2.判断是否是PC
  function isPC(){
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone",
                    "SymbianOS", "Windows Phone",
                    "iPad", "iPod"];
        var flag = true;
        for (var i = 0; i < Agents.length; i++) {
            if (userAgentInfo.indexOf(Agents[i]) > 0) {
                flag = false;
                break;
            }
        }
        return flag;
    },

3.写入cookie

   function addCookie(objName, objValue, objHours) {
        var str = objName + "=" + escape(objValue); //编码
        var date = new Date();
        var ms = objHours * 3600 * 1000;
        date.setTime(date.getTime() + ms);
        str += "; expires=" + date.toGMTString();
        str += '; path=/'
        document.cookie = str;
    },

4.读取cookie

   function getCookie(objName) {//获取指定名称的cookie的值
        var arrStr = document.cookie.split("; ");
        for (var i = 0; i < arrStr.length; i++) {
            var temp = arrStr[i].split("=");
            if (temp[0] == objName) return unescape(temp[1]);  //解码
        }
        return "";
    },

5.处理字符串中的转义符,将反斜杠\替换为转义符\;

  function htmlEncode(str){
        if (str.length == 0) return "";
        var s = str;
        s = s.replace(/\\/g, "\\\\");
        return s;
    },

6.处理字符串中的转义符,将<>替换为<>

     function htmlDecode(str){
        if (str.length == 0) return "";
        var s = str;  
        s = s.replace(/&/g, "&");
        s = s.replace(//g, ">");
        return s;  
    },

你可能感兴趣的:(开发常用tool)