You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript+RegEx删除字母间双撇号且保留空格旁双撇号

实现方案

完全可以用JavaScript配合正则实现该需求,核心使用零宽断言匹配仅出现在字母之间的双撇号,不会误处理相邻空格的场景。

正则逻辑

使用的匹配规则为:
/(?<=[a-zA-Z])''(?=[a-zA-Z])/g
各部分含义:

  • (?<=[a-zA-Z]):反向肯定预查,要求双撇号的前一个字符必须是英文字母
  • '':匹配目标双撇号
  • (?=[a-zA-Z]):正向肯定预查,要求双撇号的后一个字符必须是英文字母
  • 末尾的g为全局匹配标识,会替换文本中所有符合规则的双撇号

示例代码

// 测试用例
const testStr1 = "Test''s";
const testStr2 = "!= ''";
const testStr3 = "Test''s example != '' hello''world";

// 替换方法
function replaceQuotes(str) {
  return str.replace(/(?<=[a-zA-Z])''(?=[a-zA-Z])/g, "'");
}

console.log(replaceQuotes(testStr1)); // 输出:Test's
console.log(replaceQuotes(testStr2)); // 输出:!= ''
console.log(replaceQuotes(testStr3)); // 输出:Test's example != '' hello'world

扩展适配

  1. 多语种字母适配:如果需要适配中文、希腊字母等其他语种的字母场景,可以将正则中的[a-zA-Z]替换为Unicode字母匹配符\p{L},同时添加u修饰符启用Unicode匹配:
    /(?<=\p{L})''(?=\p{L})/gu
  2. 旧环境兼容:如果需要兼容ES2018之前的旧JS环境(不支持零宽后向断言),可以使用捕获组方案实现相同效果:
str.replace(/([a-zA-Z])''([a-zA-Z])/g, "$1'$2")

内容的提问来源于stack exchange,提问作者Milan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:54:02