ES6中如何将字符串指定字符替换为--[字符]--格式
ES6 实现指定字符集合格式化替换
需求说明
将给定字符串内属于指定字符集合的每一个字符,替换为--[对应字符]--的格式:
示例输入:原字符串
tb23a,指定待替换字符集合为t3a
期望输出:--t--b2--3----a--
代码实现
这里选择用Set存储待匹配字符,时间复杂度为O(n),同时避开动态正则的转义问题,适配所有字符场景:
const replaceSpecifiedChars = (originalStr, targetChars) => { const targetSet = new Set(targetChars); return originalStr.replace(/./g, char => targetSet.has(char) ? `--${char}--` : char ); }
也可以用Array.from遍历实现,逻辑更直观:
const replaceSpecifiedChars = (originalStr, targetChars) => { const targetSet = new Set(targetChars); return Array.from(originalStr) .map(char => targetSet.has(char) ? `--${char}--` : char) .join(''); }
验证测试
console.log(replaceSpecifiedChars('tb23a', 't3a')); // 输出结果:--t--b2--3----a--
内容的提问来源于stack exchange,提问作者octavemirbeau
相关产品推荐
相关产品推荐

