欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

个人工具库(持续更新中)

程序员文章站 2022-03-07 17:04:43
主要分享自己日常工作中常用的工具函数,希望能够对大家有帮助。工具函数不定时持续更新中…… ......

本篇目录:

  • 1.截取指定字节数的字符串
  • 2.判断是否微信
  • 3.获取时间格式的几个举例
  • 4.获取字符串字节长度
  • 5.对象克隆、深拷贝
  • 6.组织结构代码证验证
  • 7.身份证号验证
  • 8.js正则为url添加http标识
  • 9.url有效性校验方法
  • 10.自定义jsonp方法
  • 11.cookie操作
  • 12.生成随机字符串 (可指定长度)
  • 13.浏览器判断
  • 14.rem移动端适配
  • 15.获取url后参数
  • 16.动态加载js
  • 17.生成随机颜色值
  • 18.事件绑定与解绑
  • 19.移动端音频播放
  • 20.移动端视频适配
  • 21.webpack+vue-cli实现自动全局注册组件

1.截取指定字节数的字符串

/**
 * 截取指定字节的字符串
 * @param str 要截取的字符穿
 * @param len 要截取的长度,根据字节计算
 * @param suffix 截取前len个后,其余的字符的替换字符,一般用“…”
 * @returns {*}
 */
function cutstring(str, len, suffix) {
  if (!str) return "";
  if (len <= 0) return "";
  if (!suffix) suffix = "";
  var templen = 0;
  for (var i = 0; i < str.length; i++) {
    if (str.charcodeat(i) > 255) {
      templen += 2;
    } else {
      templen++
    }
    if (templen == len) {
      return str.substring(0, i + 1) + suffix;
    } else if (templen > len) {
      return str.substring(0, i) + suffix;
    }
  }
  return str;
}

2.判断是否微信

/**
 * 判断微信浏览器
 * @returns {boolean}
 */
function isweixin() {
  var ua = window.navigator.useragent.tolowercase();
  if (ua.match(/micromessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
}

3.获取时间格式的几个举例

function gettimeformat(time) {
  var date = new date(parseint(time) * 1000);
  var month, day, hour, min;
  parseint(date.getmonth()) + 1 < 10 ? month = '0' + (parseint(date.getmonth()) + 1) : month = parseint(date.getmonth()) + 1;
  date.getdate() < 10 ? day = '0' + date.getdate() : day = date.getdate();
  date.gethours() < 10 ? hour = '0' + date.gethours() : hour = date.gethours();
  date.getminutes() < 10 ? min = '0' + date.getminutes() : min = date.getminutes();
  return [month, day].join('-') + '  ' + hour + ':' + min
}

function gettimeformatymd(time) {
  var date = new date(parseint(time) * 1000);
  var year, month, day;
  year = date.getfullyear();
  parseint(date.getmonth()) + 1 < 10 ? month = '0' + (parseint(date.getmonth()) + 1) : month = parseint(date.getmonth()) + 1;
  date.getdate() < 10 ? day = '0' + date.getdate() : day = date.getdate();
  return [year, month, day].join('-')
}

function gettimeformatall(time) {
  var date = new date(parseint(time) * 1000);
  var year, month, day, hour, min, second;
  year = date.getfullyear();
  parseint(date.getmonth()) + 1 < 10 ? month = '0' + (parseint(date.getmonth()) + 1) : month = parseint(date.getmonth()) + 1;
  date.getdate() < 10 ? day = '0' + date.getdate() : day = date.getdate();
  date.gethours() < 10 ? hour = '0' + date.gethours() : hour = date.gethours();
  date.getminutes() < 10 ? min = '0' + date.getminutes() : min = date.getminutes();
  date.getseconds() < 10 ? second = '0' + date.getseconds() : second = date.getseconds();

  return [year, month, day].join('-') + '  ' + hour + ':' + min + ':' + second
}

4.获取字符串字节长度

/**
 * 获取字符串字节长度
 * @param {string}
 * @returns {boolean}
 */
function checklength(v) {
  var reallength = 0;
  var len = v.length;
  for (var i = 0; i < len; i++) {
    var charcode = v.charcodeat(i);
    if (charcode >= 0 && charcode <= 128) reallength += 1;
    else reallength += 2;
  }
  return reallength;
}

5.对象克隆、深拷贝

/**
 * 对象克隆&深拷贝
 * @param obj
 * @returns {{}}
 */
function cloneobj(obj) {
  var newo = {};
  if (obj instanceof array) {
    newo = [];
  }
  for (var key in obj) {
    var val = obj[key];
    newo[key] = typeof val === 'object' ? arguments.callee(val) : val;
  }
  return newo;
};

克隆拷贝增强版

/**
 * 对象克隆&深拷贝
 * @param obj
 * @returns {{}}
 */
function clone(obj) {
  // handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;
  // handle date
  if (obj instanceof date) {
    var copy = new date();
    copy.settime(obj.gettime());
    return copy;
  }
  // handle array
  if (obj instanceof array) {
    var copy = [];
    for (var i = 0,
    len = obj.length; i < len; ++i) {
      copy[i] = clone(obj[i]);
    }
    return copy;
  }
  // handle object
  if (obj instanceof object) {
    var copy = {};
    for (attr in obj) {
      if (obj.hasownproperty(attr)) copy[attr] = clone(obj[attr]);
    }
    return copy;
  }
  throw new error("unable to copy obj! its type isn't supported.");
}

测试用例:

var origin = {
  a: "text",
  b: null,
  c: undefined,
  e: {
    f: [1, 2]
  }
}

6.组织结构代码证验证

验证规则:

组织机构代码是每一个机关、社会团体、企事业单位在全国范围内唯一的、始终不变的法定代码标识。最新使用的组织机构代码在1997年颁布实施,由8位数字(或大写拉丁字母)本体代码和1位数字(或大写拉丁字母)校验码组成。本体代码采用系列(即分区段)顺序编码方法。校验码按下列公式计算:8 c9 = 11 - mod(∑ci * wi,11)… (2) i = 1其中:mod——表示求余函数;i——表示代码字符从左到右位置序号;ci——表示第i位置上的代码字符的值,采用附录a“代码字符集”所列字符;c9——表示校验码;wi——表示第i位置上的加权因子,其数值如下表:i 1 2 3 4 5 6 7 8 wi 3 7 9 10 5 8 4 2当mod函数值为1(即c9 = 10)时,校验码用字母x表示。

验证方法:

checkorgcodevalid: function(el) {
  var txtval = el.value;
  var values = txtval.split("-");
  var ws = [3, 7, 9, 10, 5, 8, 4, 2];
  var str = '0123456789abcdefghijklmnopqrstuvwxyz';
  var reg = /^([0-9a-z]){8}$/;
  if (!reg.test(values[0])) {
    return false
  }
  var sum = 0;
  for (var i = 0; i < 8; i++) {
    sum += str.indexof(values[0].charat(i)) * ws[i];
  }
  var c9 = 11 - (sum % 11);
  var yc9 = values[1] + '';
  if (c9 == 11) {
    c9 = '0';
  } else if (c9 == 10) {
    c9 = 'x';
  } else {
    c9 = c9 + '';
  }
  return yc9 == c9;
}

7.身份证号验证

/**
 * 验证身份证号
 * @param el 号码输入input
 * @returns {boolean}
 */
function checkcardno(el) {
  var txtval = el.value;
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|x|x)$)/;
  return reg.test(txtval)
}

8.js正则为url添加http标识

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit">
  <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1">  
  <title></title>
  <script>
        var html = 'http:/ / www.google.com ';
        html += '\rwww.google.com ';
        html += '\rcode.google.com ';
        html += '\rhttp: //code.google.com/hosting/search?q=label%3apython';
        var regex = /(https?:\/\/)?(\w+\.?)+(\/[a-za-z0-9\?%=_\-\+\/]+)?/gi;
        alert('before replace:');
        alert(html);
        html = html.replace(regex,
            function(match, capture) {
                if (capture) {
                    return match
                } else {
                    return 'http://' + match;
                }
            });
        alert('after replace:');
        alert(html); 
    </script>
</head>
<body>  
</body>
</html>

9.url有效性校验方法

/**
 * url有效性校验
 * @param str_url
 * @returns {boolean}
 */
function isurl(str_url) { 
  // 验证url
  var strregex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //           
  ftp的user@ + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // ip形式的url- 199.194.52.184
  + "|" // 允许ip和domain(域名)
  + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
  + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
  + "[a-z]{2,6})" // first level domain- .com or .museum
  + "(:[0-9]{1,4})?" // 端口- :80
  + "((/?)|" // a slash isn't required if there is no file name
  + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
  var re = new regexp(strregex);
  return re.test(str_url);
}
// 建议的正则
functionisurl(str) {
  return !! str.match(/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[a-za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[a-za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g);
}

10.自定义jsonp方法

/**
 * 自定义封装jsonp方法
 * @param options
 */
jsonp = function(options) {
  options = options || {};
  if (!options.url || !options.callback) {
    throw new error("参数不合法");
  }
  //创建 script 标签并加入到页面中
  var callbackname = ('jsonp_' + math.random()).replace(".", "");
  var ohead = document.getelementsbytagname('head')[0];
  options.data[options.callback] = callbackname;
  var params = formatparams(options.data);
  var os = document.createelement('script');
  ohead.appendchild(os);
  //创建jsonp回调函数
  window[callbackname] = function(json) {
    ohead.removechild(os);
    cleartimeout(os.timer);
    window[callbackname] = null;
    options.success && options.success(json);
  };
  //发送请求
  os.src = options.url + '?' + params;
  //超时处理
  if (options.time) {
    os.timer = settimeout(function() {
      window[callbackname] = null;
      ohead.removechild(os);
      options.fail && options.fail({
        message: "超时"
      });
    },
    time);
  }
};
/**
 * 格式化参数
 * @param data
 * @returns {string}
 */
formatparams = function(data) {
  var arr = [];
  for (var name in data) {
    arr.push(encodeuricomponent(name) + '=' + encodeuricomponent(data[name]));
  }
  return arr.join('&');
}

11.cookie操作

//写cookies
setcookie = function(name, value, time) {
  var strsec = getsec(time);
  var exp = new date();
  exp.settime(exp.gettime() + strsec * 1);
  document.cookie = name + "=" + escape(value) + ";expires=" + exp.togmtstring();
}
//cookie操作辅助函数
getsec = function(str) {
  var str1 = str.substring(1, str.length) * 1;
  var str2 = str.substring(0, 1);
  if (str2 == "s") {
    return str1 * 1000;
  } else if (str2 == "h") {
    return str1 * 60 * 60 * 1000;
  } else if (str2 == "d") {
    return str1 * 24 * 60 * 60 * 1000;
  }
}
//读取cookies
getcookie = function(name) {
  var arr, reg = new regexp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg)) return (arr[2]);
  else return null;
}

//删除cookies
delcookie = function(name) {
  var exp = new date();
  exp.settime(exp.gettime() - 1);
  var cval = getcookie(name);
  if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.togmtstring();
}

12.生成随机字符串 (可指定长度)

/**
 * 生成随机字符串(可指定长度)
 * @param len
 * @returns {string}
 */
randomstring = function(len) {
  len = len || 8;
  var $chars = 'abcdefghjkmnpqrstwxyzabcdefhijkmnprstwxyz2345678';
  /****默认去掉了容易混淆的字符ooll,9gq,vv,uu,i1****/
  var maxpos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charat(math.floor(math.random() * maxpos));
  }
  return pwd;
}

13.浏览器判断

function parseua() {
  var u = navigator.useragent;
  var u2 = navigator.useragent.tolowercase();
  return { //移动终端浏览器版本信息
    trident: u.indexof('trident') > -1,
    //ie内核
    presto: u.indexof('presto') > -1,
    //opera内核
    webkit: u.indexof('applewebkit') > -1,
    //苹果、谷歌内核
    gecko: u.indexof('gecko') > -1 && u.indexof('khtml') == -1,
    //火狐内核
    mobile: !!u.match(/applewebkit.*mobile.*/),
    //是否为移动终端
    ios: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/),
    //ios终端
    android: u.indexof('android') > -1 || u.indexof('linux') > -1,
    //android终端或uc浏览器
    iphone: u.indexof('iphone') > -1,
    //是否为iphone或者qqhd浏览器
    ipad: u.indexof('ipad') > -1,
    //是否ipad
    webapp: u.indexof('safari') == -1,
    //是否web应该程序,没有头部与底部
    iosv: u.substr(u.indexof('iphone os') + 9, 3),
    weixin: u2.match(/micromessenger/i) == "micromessenger",
    ali: u.indexof('aliapp') > -1,
  };
}
var ua = parseua();
if (!ua.mobile) {
  location.href = './pc.html';
}

14.rem移动端适配

var rem = {
  baserem: 40,
  // 基准字号,按照iphone6应该为20,此处扩大2倍,便于计算
  basewidth: 750,
  // 基准尺寸宽,此处是按照ihpone6的尺寸
  rootele: document.getelementsbytagname("html")[0],
  inithandle: function() {
    this.setremhandle();
    this.resizehandle();
  },
  setremhandle: function() {
    var clientwidth = document.documentelement.clientwidth || document.body.clientwidth;
    this.rootele.style.fontsize = clientwidth * this.baserem / this.basewidth + "px";
  },
  resizehandle: function() {
    var that = this;
    window.addeventlistener("resize",
    function() {
      settimeout(function() {
        that.setremhandle();
      },
      300);
    });
  }
};
rem.inithandle();

15.获取url后参数

function getrequest() {
  var url = location.search; //获取url中"?"符后的字串
  var therequest = new object();
  if (url.indexof("?") != -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      therequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
    }
  }
  return therequest;
}

16.动态加载js

function loadscript(url, callback) {
  var script = document.createelement("script");
  script.type = "text/";
  if (typeof(callback) != "undefined") {
    if (script.readystate) {
      script.onreadystatechange = function() {
        if (script.readystate == "loaded" || script.readystate == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {
      script.onload = function() {
        callback();
      };
    }
  }
  script.src = url;
  document.body.appendchild(script);
}

17.生成随机颜色值

function getrandomcolor () {
  const rgb = []
  for (let i = 0 ; i < 3; ++i){
    let color = math.floor(math.random() * 256).tostring(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}

18.事件绑定与解绑

elementclass.prototype.on = function (name, callback) {
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(callback)
}

elementclass.prototype.off = function (name, callback) {
    var callbacks = this.callbacks[name]
    if (callbacks && callbacks instanceof array) {
        var index = callbacks.indexof(callback)
        if (index !== -1) callbacks.splice(index, 1)
    }
}

elementclass.prototype.trigger = function (name, params) {
    var callbacks = this.callbacks[name]
    if (callbacks && callbacks instanceof array) {
        callbacks.foreach((cb) => {
            cb(params)
        })
    }
}

19.移动端音频播放

/**
  * 移动端h5播放音乐处理,兼容微信端
  * @param el 音乐audio元素
  */
function playmusic(el) {
    var b = document.getelementbyid(el);

    var c = function c() {
        b.play();
        document.removeeventlistener("touchstart", c, true);
    };

    b.play();
    document.addeventlistener("weixinjsbridgeready", function () {
        c();
    }, false);
    document.addeventlistener("yixinjsbridgeready", function () {
        c();
    }, false);
    document.addeventlistener("touchstart", c, true);
}

20.移动端视频适配

<video class="video1" webkit-playsinline="true" x-webkit-airplay="true" playsinline="true" x5-video-player-type="h5" x5-video-player-fullscreen="true"  preload="auto" poster="poster图片地址" src="视频地址"></video>

21.webpack+vue-cli实现自动全局注册组件

// 需要 npm import --save lodash
import upperfirst from 'lodash/upperfirst'
import camelcase from 'lodash/camelcase'

const requirecomponent = require.context(
  // 其组件目录的相对路径
  './components',
  // 是否查询其子目录
  false,
  // 匹配基础组件文件名的正则表达式,获取.vue结尾的文件
  /.vue$/
)


requirecomponent.keys().foreach(filename => {
  // 获取组件配置
  const componentconfig = requirecomponent(filename)

  // 获取组件的 pascalcase 命名
  const componentname = upperfirst(
    camelcase(
      // 剥去文件名开头的 `./` 和结尾的扩展名
      filename.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

  // 全局注册组件
  vue.component(
    componentname,
    // 如果这个组件选项是通过 `export default` 导出的,
    // 那么就会优先使用 `.default`,
    // 否则回退到使用模块的根。
    componentconfig.default || componentconfig
  )