如何用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
扩展适配
- 多语种字母适配:如果需要适配中文、希腊字母等其他语种的字母场景,可以将正则中的
[a-zA-Z]替换为Unicode字母匹配符\p{L},同时添加u修饰符启用Unicode匹配:/(?<=\p{L})''(?=\p{L})/gu - 旧环境兼容:如果需要兼容ES2018之前的旧JS环境(不支持零宽后向断言),可以使用捕获组方案实现相同效果:
str.replace(/([a-zA-Z])''([a-zA-Z])/g, "$1'$2")
内容的提问来源于stack exchange,提问作者Milan
相关产品推荐
相关产品推荐

