javascript - JS正则表达式匹配 ' but not\'

标签 javascript regex

我想替换字符串中的简单引号,但不替换转义引号(在 JavaScript 中)。例如我想要这个字符串:

'Hello there! I\'m \'Doug\''

成为:

"Hello there! I\'m \'Doug\'"

注意:我进行了大量的研究和测试(例如在 regex101.com 上)并发现了一些东西,例如 Regular expression to match a line that doesn't contain a word?但仍然不知道如何构建正确的正则表达式。

我尝试过的事情:

  • /[^\\]'/g
  • /\\{0}'/g
  • /[\\]{0}'/g
  • ...

最佳答案

您可以将此String#replacecallback函数一起使用:

str = "'Hello there! I\\'m \\'Doug\\''";
str = str.replace(/(\\)?'/g, function($0, $1) {
   return ($1) ? "\\'" : '"';
});
console.log( str );
//=> "Hello there! I\'m \'Doug\'"

关于javascript - JS正则表达式匹配 ' but not\',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184335/

相关文章:

javascript - Parse Cloud Code - 等待并返回关系查询

javascript - 为什么我不能在给定的 HTML 页面中有两个 ng-app 指令 - AngularJS?

javascript - 避免在 am 图表上重新加载动画

javascript - JS 正则表达式替换文件名中的版本号

regex - Emacs正则表达式:替换 latex 方程中的字符串

c# - word.otherword 的正则表达式

javascript - 尝试将电子邮件字段设置为只读/禁用

javascript - 一组 HTML 元素的倒序

c++ - 如何将正则表达式模式存储为正则表达式对象或字符串?

java - 为什么这个模式在java中需要很长时间才能匹配?