js常用工具函数+常用正则验证(持续更新)

220 阅读2分钟

常用工具函数

禁用滚动条 禁止页面滚动

/**
 * @Description 禁用滚动条
 * @Author luochen_ya
 * @Date 2024-12-10
 */
export function handleStopScroll () {
  var mo = function (e) { e.preventDefault() }
  document.body.style.overflow = 'hidden'
  document.addEventListener("touchmove", mo, false)
}

恢复禁用滚动条 恢复禁止页面滚动

/**
 * @Description 恢复滚动条
 * @Author luochen_ya
 * @Date 2024-12-10
 */
export function handleCanScroll () {
  var mo = function (e) { e.preventDefault() }
  document.body.style.overflow = ''
  document.removeEventListener("touchmove", mo, false)
}

数字千位符

/**
 * @Description 數字千位符
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {number} value
 * @returns {string}
 */
export function handleThousands (value) {
  const suffix = ''
  if (value && value !== 'NULL' && value !== 'undefined' && isNaN(Number(value))) {
    return value
  } else if (!value) {
    return '0'
  } else {
    const pSuffix = ''
    value = value.toString()
    const intPart = Math.floor(Math.abs(Number(value)))
    let intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    intPartFormat = pSuffix + intPartFormat
    let floatPart = ''
    const value2Array = value.split('.')
    
    if (value2Array.length === 2) {
      floatPart = value2Array[1].toString()
      if (floatPart.length === 1) {
        
        return intPartFormat + '.' + floatPart + '0' + suffix
      } else {
        return intPartFormat + '.' + floatPart + suffix
      }
    } else {
      return intPartFormat + floatPart + suffix
    }
  }
}

防抖

/**
 * @Description 防抖
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {function} func
 * @param {number} delay
 */
export function debounce (func, delay) {
  let timeoutId
  return function (...args) {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      func(...args)
    }, delay)
  }
}

节流

/**
 * @Description 节流
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {function} func
 * @param {number} delay
 */
export function throttle (func, delay) {
  let lastTime = 0;

  return function (...args) {
    const now = Date.now();

    if (now - lastTime >= delay) {
      lastTime = now;
      func(...args);
    }
  };
}

图片压缩

compressorjs官网:www.npmjs.com/package/com…

// 安装
npm install compressorjs
// 引入
import ImageCompressor from 'compressorjs'
/**
 * @Description 图片压缩
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {File} file 图片文件
 * @param {Number} maxWidth 压缩最大宽度,超出按比例缩小
 * @param {Number} maxHeight 压缩最大高度,超出按比例缩小
 * @param {Number} maxSize 未压缩图片最大尺寸,超出该尺寸则进行压缩
 * @param {Number} quality 压缩质量 0-1
 * @returns <Promise> 压缩后的图片信息
 */
export function publicImageCompression (file, maxWidth = 2000, maxHeight = 2000, maxSize = 5, quality = 1) {
  return new Promise((resolve, reject) => {
    const options = {
      success(result) {
        resolve(result);
      },
      error(e) {
        reject(e);
      },
    };
    if (file.size > maxSize * 1024 * 1024) {
      options.quality = quality
      options.maxWidth = maxWidth
      options.maxHeight = maxHeight
      options.convertSize = true
    }
    new ImageCompressor(file, options);
  })
}

大小写字母+数字 N位随机码

/**
 * @Description N位随机码
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {number} length
 * @returns {number} 随机字符串
 */
export function generateRandomString (length) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

获取音频的时长

/**
 * @Description 获取音频时长
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {string} audioSrc
 * @returns {number} 音频时长
 */
export function getAudioDuration (audioSrc) {
  let audioDuration = 0
  let audioObject = new Audio(audioSrc);

  audioObject.addEventListener('loadedmetadata', () => {
    audioDuration = audioObject.duration;
    audioObject = null; // 清理资源
  });

  audioObject.addEventListener('error', () => {
    console.error('无法加载音频');
    audioObject = null; // 清理资源
  })
  return audioDuration
}

常用正则验证函数

验证中文字符格式

/**
 * @Description 验证中文字符格式
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {string} str
 * @returns {Boolean}
 */
export function validChinese (str) {
  const reg = /^[\u4e00-\u9fa5]+$/
  return reg.test(url)
}

验证网址URL格式

/**
 * @Description 验证网址URL格式
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {string} url
 * @returns {Boolean}
 */
export function validURL (url) {
  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return reg.test(url)
}

验证邮箱格式

/**
 * @Description 验证邮箱格式
 * @Author luochen_ya
 * @Date 2024-12-10
 * @param {string} email
 * @returns {Boolean}
 */
export function validEmail (email) {
  const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return reg.test(email)
}