前端 utils 会用到的一些方法,持续更新...

105 阅读1分钟
/*数字千分位处理*/
Vue.prototype.checkMoney = function (val){
  val = val.replace(/[^\d.-]/g,"");//清除"数字"和"."以外的字符
  val = val.replace(/^\./g,"");//验证第一个字符是数字而不是字符
  val = val.replace(/\.{2,}/g,".");//只保留第一个.清除多余的
  val = val.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
  val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
  return val
}
 // 格式化金额
Vue.prototype.formatMoney = function(val){
  if(!val) {
    return "0.00"
  }
  let str = parseFloat(val).toFixed(2) + '';
  let intSum = str.substring(0,str.indexOf(".")).replace( /\B(?=(?:\d{3})+$)/g, ',' );//取到整数部分
  let dot = str.substring(str.length,str.indexOf("."))//取到小数部分搜索

  return intSum + dot;
}
// 判断是不是promise
function isPromise (val) {
    return (
      isDef(val) &&
      typeof val.then === 'function' &&
      typeof val.catch === 'function'
    )
  }
function isObject (obj) {
    return obj !== null && typeof obj === 'object'
}
function isUndef (v) {
    return v === undefined || v === null
}
function isDef (v) {
    return v !== undefined && v !== null
  }

// 是否以$ || _ 开头 
function isReserved (str) {
    var c = (str + '').charCodeAt(0);
    return c === 0x24 || c === 0x5F
  }
// 富文本数据 去除标签内容
function filterEditorDataTab(str) {
    return str.replace(/<[^>]+>/g, "")
}
// 输入框金额保留两位小数
input_value: function (newVal, oldVal) {
  if (this.check_money && newVal != oldVal) {
    this.input_value = (newVal + "")
      .replace(/[^\d.-]/g, "")
      .replace(/^\./g, "")
      .replace(/\.{2,}/g, ".")
      .replace(/\-{2,}/g, "-")
      .replace(".", "$#$")
      .replace(/\./g, "")
      .replace("$#$", ".")
      .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
  }
},
vue 里的
// 1、蛇形命名  转 驼峰

function cached (fn){
  const cache = Object.create(null)
  return function cachedFn(str) {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }
}

/**
 * Camelize a hyphen-delimited string.
 */
const camelizeRE = /-(\w)/g
const camelize = cached((str) => {
  return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
});


// const name = camelize('aaa');
// const name1 = camelize('-aaa');
// const name2 = camelize('bbb');
// const name3 = camelize('c-cc');
// const name4 = camelize('aa-a');
// console.log('------name', name);
// console.log('------name1', name1);
// console.log('------name2', name2);
// console.log('------name3', name3);
// console.log('------name4', name4);