我想替换字符串中的简单引号,但不替换转义引号(在 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#replace
与callback
函数一起使用:
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/