删除所有不在单引号或双引号之间的调试器

Remove all debuggers that ARE NOT between single or double quotes

我正在尝试实现一个从文件中删除所有调试器的正则表达式,除非该调试器在...

  1. 单引号
  2. 双引号

我有以下适用于双引号的代码,但我不确定如何也包含单引号。

var removeDebuggers = (str) => {

  str = str.replace(/debugger(?=([^"]*"[^"]*")*[^"]*$)/g, "");

  console.log(str)

}

removeDebuggers(`
  Here is a 'debugger' in single quotes. 
  - DOESN'T WORK.
  Another "debugger test" but with double quotes.
  - WORKS.
  "Testing this debugger also." 
  - WORKS.
  My final debugger not in quotes. 
  - WORKS.
  `)

我正在努力的结果是“Here is a 'debugger' in single quotes.”中的调试器也不会被删除。任何不在双引号或单引号内的 debugger 都应该单独保留。

当您在所有上下文中删除一个字符串但在单引号或双引号内时,更容易匹配引号并将它们捕获在一个组中以便稍后在结果字符串中恢复,并在替换模式中对该组进行反向引用:

str = str.replace(/("[^"]*"|'[^']*')|debugger/g, "");

参见regex demo

详情

  • ("[^"]*"|'[^']*') - 第 1 组(从替换模式中引用 </code>): <ul> <li><code>"[^"]*" - ",除 " 之外的 0 个或更多字符,然后是 "
  • | - 或
  • '[^']*' - ',除 ' 之外的 0 个或更多字符,然后是 '
  • | - 或
  • debugger - 一个子字符串。
  • 要将 debugger 作为一个完整的单词进行匹配,请使用单词边界,\bdebugger\b

    为了支持 single/double 引号内的转义序列,将 ("[^"]*"|'[^']*') 模式扩展为 ("[^"\]*(?:\[\s\S][^"\]*)*"|'[^'\]*(?:\[\s\S][^'\]*)*')。或者,更好的是 ((?:^|[^\/])(?:\{2})*"[^"\]*(?:\[\s\S][^"\]*)*"|'[^'\]*(?:\[\s\S][^'\]*)*').

    所以,增强版看起来像

    str = str.replace(/((?:^|[^\/])(?:\{2})*"[^"\]*(?:\[\s\S][^"\]*)*"|'[^'\]*(?:\[\s\S][^'\]*)*')|\bdebugger\b/g, '');
    

    参见 this regex demo