【问题标题】:javascript: find by pattern and replacejavascript:按模式查找并替换
【发布时间】:2019-04-03 11:41:37
【问题描述】:

我有一个字符串,看起来像:'[bla] asf bla qwr bla' 其中bla 是未知的。我需要找到所有出现的bla(或其他)。 我可以使用 js 在几个命令中做到这一点:

const s = '[bla] asf bla qwr bla';
const pattern = s.match(/(?<=\[).*(?=\])/)[0]
return s.replace(new RegExp(pattern, 'g'))

是否可以在一个正则表达式中完成? bla 未知,我只知道括号。任何东西都可以放在括号中。

【问题讨论】:

  • 这需要两个步骤,对。 1)找到要替换的值,2)替换值。
  • 不,不可能。
  • 你想用什么替换[]中的内容?
  • 任何字符串都无所谓
  • 我们应该替换所有 3 个 bla 还是只替换 [] 中的那个?

标签: javascript node.js regex negative-lookahead


【解决方案1】:

试试:

const s = '[bla] asf bla qwr bla';
const r = s.replace(/(?<=\[)[^\]]*(?=\])/i, "test");
console.log(r);

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    相关资源
    最近更新 更多