javascript代码片段

2022/12/10 javascript

# 字符串操作

首字母转大写

str.replace(str[0], str[0].toUpperCase())

随机颜色

export const randomColor = () => {
    let color = '#';
    const arr = window.crypto.getRandomValues(new Uint8Array(3));
    for (const item of arr) {
        color += item.toString(16);
    }
    return color;
};

生成随机字符串

export const randomString = (len) => {
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
    let strLen = chars.length;
    let randomStr = '';
    for (let i = 0; i < len; i++) {
        randomStr += chars.charAt(Math.floor(Math.random() * strLen));
    }
    return randomStr;
};

补零

(Array(3).join('0') + String(id)).slice(-3)

将十进制转换为二进制文件或十六进制数

const num = 45
num.toString(2)
num.tostring(16)

交换变量的值

let bears = 'bears'
let tigers = 'tigers'
[bears, tigers] = [tigers, bears]

# 数组操作

打乱数组顺序

let arr = [67, true, false, '55']
arr = arr.sort(() => 0.5 - Math.random())
console.log(arr)

删除数组重复的元素

const animals = ['bears', 'lions', 'tigers', 'bears', 'lions']
const unique = (arr) => [...new Set(arr)]

console.log(unique(animals))

过滤数组中值为 false 的值

const nums = [1, 0 , undefined, null, false];
const truthyNums = nums.filter(Boolean);
console.log(truthyNums) // [1]

# 格式校验

校验身份证号码

export const checkCardNo = (value) => {
    let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return reg.test(value);
};

校验是否包含中文

export const haveCNChars => (value) => {
    return /[\u4e00-\u9fa5]/.test(value);
}

校验是否为中国大陆的邮政编码

export const isPostCode = (value) => {
    return /^[1-9][0-9]{5}$/.test(value.toString());
}

校验是否为IPv6地址

export const isIPv6 = (str) => {
    return Boolean(str.match(/:/g)?str.match(/:/g).length<=7:false && /::/.test(str)?/^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$/i.test(str):/^([\da-f]{1,4}:){7}[\da-f]{1,4}$/i.test(str));
}

校验是否为邮箱地址

export const isEmail = (value) {
    return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
}

校验是否为中国大陆手机号

export const isTel = (value) => {
    return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString());
}