js 封装常用方法【持续更新】

 
/*

  @@ 判断字符串是否为空
  example: isNull('三毛')
  return: true为空

*/
export const isNull = (str)=>{//
    return str == null || str.length === 0 || str === '';
}




/*

  @@ 是否为邮箱地址
  example: isEmail('[email protected]')
  return: true
*/
export const isEmail = (str)=>{
    return /^\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(str)
}


/*

  @@ 是否为手机号码
  example: isPhone('18888888888')
  return: true

*/
export const isPhone = (str)=>{
    return /^1\d{10}$/.test(str)
}



/*

  @@ 是否为纯汉字
  example: isCN('三毛')
  return: true
*/
export const isCN = (str)=>{
    return /^[\u4e00-\u9fa5]+$/.test(str)
}




/*

  @@ 是否为纯数字
  example: isNum('123456')
  return: true
*/
export const isNum = (str)=>{
    return /^[0-9]+$/.test(str)
}



/*

  @@ 是否为Url
  example: isUrl('https://www.baidu.com')
  return: true
*/
export const isUrl = (str)=>{
    return /^(http|https){1}:\/\/[^\s]+$/.test(str)
}



/*
 @@ 去掉字符串所有空格
 example: stringTrim('   11   ')
 return "11"
 */
//去字符串所有空格
export const stringTrim = (str)=>{
  return Str.replace(/(^\s+)|(\s+$)/g, '')
}




/*
  @@ 格式化数字格式
  @param s为要格式化的number
  @param n为要保留几位小数点
  @param m为最大数
  example: formatNum(66.6666,2)
  return "66.66"
*/
export const formatNum = (s, n, m) => {

  if(s > m) return m;//超过100归置为100
  n = n > 0 && n <= 20 ? n : 2
  s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + ''
  var l = s.split('.')[0].split('').reverse(), r = s.split('.')[1]
  let t = ''
  for (let i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? ',' : '')
  }
    return t.split('').reverse().join('') + '.' + r
}




/*

  @@ 密文形式手机号码
  @param num手机号码
  example: passwordPhone(18888888888)
  return: "150****7126"
*/
export const passwordPhone  = (num)=>{
    return num.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}



/*

  @@ 获取url后面参数
  example: isNull('https://www.baidu.com?id=1&name=gsx')
  return: { id:1, name:gsx }
*/
export const  ParseUrlQuery = () => {//
    var result = {};
    var url = window.location.href;
    var query = url.split("?")[1];
    if (query) {
      var queryArr = query.split("&");
      queryArr.forEach(function (item) {
        var key = item.split("=")[0];
        result[key] = item.split("=")[1];
      });
    }

    return result;
}




/*

  @@ 判断是否为PC端
  return: true为PC
*/
export const  IsPC = ()=> {
  let userAgentInfo = navigator.userAgent
  let Agents = [
    'Android',
    'iPhone',
    'SymbianOS',
    'Windows Phone',
    'iPad',
    'iPod'
  ]
  let flag = true
  for (let v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false
      break
    }
  }
    return flag
}

发布了9 篇原创文章 · 获赞 3 · 访问量 1033

猜你喜欢

转载自blog.csdn.net/m0_38102288/article/details/103051229