字符串去除空格,数组去重,对象深拷贝的函数

今天写了几个字符串去除空格,数组去重,对象深拷贝的函数



/**
 * 去除首尾空格
 * @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)
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值