学无先后,达者为师

网站首页 前端文档 正文

js字符串函数substr替换使用技巧

作者:白菜new 更新时间: 2022-01-06 前端文档

替换字符串

前言

最近在业务场景中有些电话号码、银行卡等信息需要将中间几位替换为*,自然的想到了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, '****')

原文链接:https://blog.csdn.net/qq_43850819/article/details/118524438

栏目分类
最近更新