UNPKG

zpy-tools

Version:

提供了日期格式化、日期计算、文件格式化、本地缓存处理、Base64转File、File转Base64、节流防抖、数组排序、数据结构转化、深度比较两个对象是否包含相同的值等相关功能

109 lines (90 loc) 2.97 kB
/** * 检查值是否为空 * @param {*} value - 要检查的值 * @returns {Boolean} - 如果值为空,则返回 true;否则返回 false */ function isEmpty(value) { // 处理基本类型 if (value === null || value === undefined || value === '') { return true; } // 检查布尔和数字类型 if (typeof value === 'boolean' || typeof value === 'number') { return false; } // 检查数组 if (Array.isArray(value)) { return value.length === 0; } // 检查对象(包括 Date, RegExp 等) if (typeof value === 'object') { // 对于对象,检查是否有自己的可枚举属性 return Object.keys(value).length === 0 && value.constructor === Object; } // 其他类型的值默认不为空 return false; } /** * 检查是否为合法的URL * @param {string} url - 要检查的URL字符串 * @returns {Boolean} - 如果是合法的URL,则返回 true;否则返回 false */ function isURL(url) { // 参数验证 if (typeof url !== 'string') { throw new TypeError('The argument must be a string.'); } // 处理空字符串和空白字符 const trimmedUrl = url.trim(); if (trimmedUrl === '') { return false; } // 增强的正则表达式,支持更多合法的URL格式 const regex = /^(http|https):\/\/[\w.-]+(?:\:[\d]+)?(?:\/[^\s]*)?$/; return regex.test(trimmedUrl); } /** * 检查是否为合法的电子邮件地址 * @param {string} email - 要检查的电子邮件字符串 * @returns {Boolean} - 如果是合法的电子邮件,则返回 true;否则返回 false */ function isEmail(email) { // 参数验证 if (typeof email !== 'string') { throw new TypeError('The argument must be a string.'); } // 处理空字符串和空白字符 const trimmedEmail = email.trim(); if (trimmedEmail === '') { return false; } // 增强的正则表达式,支持更多合法的电子邮件格式 const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; return regex.test(trimmedEmail.toLowerCase()); } /** * 检查是否为合法的中国手机号码 * @param {string|number} phone - 要检查的手机号码,可以是字符串或数字 * @returns {Boolean} - 如果是合法的手机号码,则返回 true;否则返回 false */ function isMobile(phone) { // 参数验证 if (typeof phone !== 'string' && typeof phone !== 'number') { throw new TypeError('The argument must be a string or a number.'); } // 将 phone 转换为字符串,并去除两端空白字符 const phoneStr = String(phone).trim(); // 处理空字符串或无效数字 if (phoneStr === '' || isNaN(phoneStr)) { return false; } // 正则表达式,匹配中国手机号码 const regex = /^1[3-9]\d{9}$/; return regex.test(phoneStr); } module.exports = { isEmpty, isURL, isEmail, isMobile };