今天写了几个字符串去除空格,数组去重,对象深拷贝的函数
/**
* 去除首尾空格
* @param {*} str
* @returns
* @example
* trim(" a c " ) --> "a c"
*/
const trim = str => str ? str.replace(/(^\s*)|(\s*$)/g,"") : '';
/**
* 去除字符串左侧空格
* @param {*} str
* @returns
* @example
* trimL(" a c " ) --> "a c "
*/
const trimL = str => str ? str.replace(/(^\s*)/g,"") : '';
/**
* 去除字符串右侧空格
* @param {*} str
* @returns
* @example
* trimR(" a c " ) --> " a c"
*/
const trimR = str => str ? str.replace(/(\s*$)/g,"") : '';
/**
* 去除字符串的中文和空格
* @param {*} str
* @returns
* @example
* trimCn(" 人2的 人cd" ) --> "2cd"
*/
const trimCn = str => str.replace(/[\u4e00-\u9fa5\s]+/g, '');
/**
* 深度拷贝 注意:该方法无法拷贝函数、正则表达式等特殊对象类型
* @param {*} obj 可以是字符串,数组实例,对象实例,
* @returns
*/
const clone = (obj) =>{
return JSON.parse(JSON.stringify(obj));
}
//数组
/**
* 数组去重
* @param {*} arr
* @returns []
* @des 可以去重任意类型的数据,也支持混合的元数据类型,甚至二维数组
* @example
* unique([ 1,1,2 ])) --> [ 1,2 ]
* unique([ [1], [1],[2] ])) --> [ [1],[2] ]
* unique([ {"name":"tom"}, {"name":"tom"} ])) --> [ {"name":"tom"} ]
* unique([ {"name":"tom"}, {"name":"tom"}, [1],[1],[2], 3, 4 ])) --> [ {"name":"tom"}, [1],[2], 3, 4 ]
*/
const unique = arr => Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse)
module.exports = {
trim,
trimL,
trimR,
trimCn,
clone,
unique
}
setTimeout(function(){
let t = trim(" a c ")
let tL = trimL(" a c ")
let tR = trimR(" a c ")
console.log(t)
console.log(tL)
console.log(tR)
console.log(unique([1, "2", 2, 2, 1]))
console.log(unique([{"name":"tom"}, {"name":"tom"}, [1], [1],[2], 3, 4]))
console.log(trimCn(" 打2的 法c dd d的 d"))
let ar1 = {"tom":'adf', "arr":[2], "c":function(){console.log("ccc")}}
let ca1 = clone(ar1)
ar1.tom = "aaa"
console.log("ar1", ar1)
console.log("ca1", ca1)
console.log("ca2", clone("safd"))
}, 2000)