为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 javascript 中执行正则表达式查找和替换,它交替“替换”和“查找下一个”

如何在 javascript 中执行正则表达式查找和替换,它交替“替换”和“查找下一个”

侃侃无极 2021-12-02 16:35:50
我可以在 Editpad 中通过运行宏交替“查找下一个”和“替换当前并查找下一个”来完成。但是,我有很多正则表达式文本替换来执行此操作,因此为每个替换都非常耗时。如果我想一次完成所有这些,我可以在 javascript 中全局执行,但我想要做的是替换一个,跳过下一个,替换下一个,依此类推到文档末尾。我试过在谷歌上搜索答案,但所有结果都是关于查找和替换每次出现的,我已经知道该怎么做。
查看完整描述

2 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

String.prototype.replace()就是你要找的,mdn。


let replaceEveryOther = (string, replaced, repalceWith) => {

  let alternate;

  return string.replace(replaced, a =>

    (alternate = !alternate) ? repalceWith : a);

};


let string = 'thee doublee ee\'s neeeed to be fixeed soon!';

let fixed = replaceEveryOther(string, /e/g, '');

console.log(fixed);


查看完整回答
反对 回复 2021-12-02
?
慕娘9325324

TA贡献1783条经验 获得超4个赞

或者,如果您想避免使用辅助函数:


let string = 'thee doublee ee\'s neeeed to be fixeed soon!';

let fixed = string.replace(/e/g, (function(a) {

  return (this.alternate = !this.alternate) ? '' : a;

}).bind({}));

console.log(fixed);


查看完整回答
反对 回复 2021-12-02
  • 2 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信