本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前言
由于JavaScript是一种解释型编程语言,声明变量并不需要定义类型,变量可以随时更改存储数据的类型。
我们都知道 typeof 可以判断数据类型,但遇到 null 、array等其他数据类型时,就需要用到更为详细的toString了
业务场景中有些电话号码、银行卡等信息需要将中间几位替换为*,自然的想到了substr。 正好一起整理了。
substr
substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。 stringObject.substr(start,length)
一、思路
我们从传入的参数有4个
/**
* @param {string} str 原字符串
* @param {number} start 开始替换的位置
* @param {number} stop 停止替换的位置
* @param {string} replace 替换的字符串
*/
const replaceStr = (str, start, stop, replace) => {
return str.substr(0, start - 1) + replace + str.substr(stop)
}
replaceStr('测试abcd文字', 3, 6, '****') // 测试****文字
通过 substr 从 原字符串 中获取首位到开始替换位置前的字符串,接着加入替换的字符串,再通过 substr 获取 原字符串 停止替换后的其他字符串,组合返回。
二、运用
当电话号码需要隐藏中间4位时,我们便可以这样运用
function filterPhone(phone) {
return replaceStr(phone, 4, 7, '****')
}
const myPhone = '1361234001'
filterPhone(myPhone) // 136****001
小白式使用方法
在使用时,不需要管下标是什么,怎么简单怎么来 通过这个公式
end - start + 1 = 替换多少位
只需知道从第几位开始替换,替换多少位就能推导停止替换的位置
例子: 从第6位开始,需要替换4位
end = 6 + 4 - 1
replaceStr(text, 6, 9, '****')
一、toString
toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的[[Class]]。其格式为[object Xxx] ,其中 Xxx 即为目标的类型
二、上代码
function typeOf(target){
// Object.prototype.toString.call(target) 通过此便可获得目标的[[Class]]
// 再由正则匹配 就能获得目标的类型
// toLocaleLowerCase()将其转换为小写 留到下面扩展用
return /^\[object (\w+)]$/.exec(Object.prototype.toString.call(target))[1].toLocaleLowerCase()
}
//原生typeof
typeOf(new Set()) //object
typeof(null) // object
typeOf(new Set()) //set
typeOf(null) //null
自此,利用 toString 封装的 typeOf 函数便能判断所有的js数据类型了。
三、扩展
判断变量为空
function empty(target){
if(arguments.length > 1){
// 多个值的时候判断都为空
return [...arguments].every(v => empty(v))
}else {
switch(typeOf(target)){
case 'array':
case 'string':
case 'object': return Object.keys(target).length === 0
default: return target == null
}
}
}