繁体   English   中英

RegExp 如何在此示例中替换双引号上的单引号

[英]RegExp how replace single quotes on double quotes in this example

 let text = "'I'm the cook,' he said, 'it's my job.'"; // Change this call. function replaceQuotes(string) { const actionReplace = string.replace(/(^')|('$)|('(?=.*)(?=\s))|(?: '(?=.*))/g, "#"); return actionReplace } console.log(replaceQuotes(text)); //expected result → "I'm the cook," he said, "it's my job." //actual result → "zI'm the cook,z he said,zit's my job.z"

因为"字符\ ”放在它前面。

所以你可以把"#"改成"\""

或者你可以把"#"改成“ '"'

 let text = "'I'm the cook,' he said, 'it's my job.'"; function replaceQuotes (string){ const actionReplace = string.replace(/(^')|('$)|('(?=.*)(?=\s))/g, "\"").replace(/(?: '(?=.*))/g, " \""); return actionReplace } console.log(replaceQuotes(text))

在最后一个交替中,您有一个未被替换的空间。

只需在替换部分添加这个空间,为此,我已经删除了所有无用的组(这会减慢进程)并创建另一个包含要保留的空间的组。

 let text = "'I'm the cook,' he said, 'it's my job.'"; // Change this call. function replaceQuotes(string) { const actionReplace = string.replace(/^'|'$|'(?=\s)|( )'(?=.*)/g, '$1"'); return actionReplace } console.log(replaceQuotes(text)); //expected result → "I'm the cook," he said, "it's my job." //actual result → "zI'm the cook,z he said,zit's my job.z"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM