如何在JavaScript中用正则匹配引号内内容并替换(排除外部内容)
解决JavaScript中匹配双引号内内容并替换的问题
你的问题出在正则的贪婪匹配上:.+会尽可能匹配最长的内容,所以会从第一个双引号一直匹配到最后一个双引号,而非每个独立的引号对。
下面是两种可靠的解决方案:
方案1:使用非贪婪匹配正则
通过在.+后添加?,将贪婪匹配转为非贪婪匹配,让正则匹配到下一个双引号就停止:
const originalStr = 'The receptionist: "Okay, please wait a moment." After a while, the receptionist smiled and said, "Congratulations, you have obtained a certificate of exemption from the exam for job transfer. With it, you can use it after you reach a certain Level. After completing the job transfer task, you can directly transfer to a specific occupation, a very convenient little gift."'; // 替换引号内的内容,示例:转为大写 const replacedStr = originalStr.replace(/"(.+?)"/g, (fullMatch, innerContent) => { return `"${innerContent.toUpperCase()}"`; }); console.log(replacedStr);
方案2:使用排除型字符集
用[^"]匹配除双引号外的任意字符,同样可以精准锁定每个引号对里的内容:
const originalStr = 'The receptionist: "Okay, please wait a moment." After a while, the receptionist smiled and said, "Congratulations, you have obtained a certificate of exemption from the exam for job transfer. With it, you can use it after you reach a certain Level. After completing the job transfer task, you can directly transfer to a specific occupation, a very convenient little gift."'; // 替换引号内的内容,示例:添加自定义前缀 const replacedStr = originalStr.replace(/"([^"]+)"/g, (fullMatch, innerContent) => { return `"【处理后:${innerContent}】"`; }); console.log(replacedStr);
关键说明
(.+?)/([^"]+):这是捕获组,用于提取引号内的实际内容,你可以在替换函数里对innerContent做任意自定义处理/g:全局标志,确保匹配所有符合条件的引号对,而非只匹配第一个
内容的提问来源于stack exchange,提问作者rarksoca
相关产品推荐
相关产品推荐

