You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:45:01