js 使用正则表达式替换以 n 开头 结束的内容改为 n aa
可以使用 replace 方法结合正则表达式来实现:
const str = 'nabc{n}nxyz{n}';
const replacedStr = str.replace(/n.*?{/g, 'n aa {');
console.log(replacedStr); // "n aa {n aa {nxyz{n}"
解释一下正则表达式:
/n.*?{/g:匹配以 n 开头,后面跟任意字符(非贪婪模式),最后以 { 结束的字符串,g 表示全局匹配。'n aa {':替换匹配到的字符串为 n aa {。
这样就能把字符串中所有符合条件的部分替换成 n aa { 了。
原文地址: https://www.cveoy.top/t/topic/e4DY 著作权归作者所有。请勿转载和采集!