如何用JavaScript正则表达式替换URL中重复的/test/路径?
解决连续
/test/无法全部替换的正则方案 你原来的正则/\/test\//g会匹配完整的/test/字符串,但当两个/test/连续出现时(比如/test/test/),第一个匹配替换成/后,剩下的字符串是/test/,但正则引擎已经处理过第一个/test/的结束位置(也就是第二个/的位置),不会回头重新匹配这个位置开始的/test/,导致第二个无法被替换。
方案1:使用正向先行断言避免消耗斜杠
通过正向先行断言(?=\/)匹配/test后面的斜杠但不消耗它,这样每次替换后,后续的斜杠还能被下一次匹配复用:
let url = "https://www.google.es/test/test/hello/world"; // 先替换所有 /test 后面跟着 / 的情况,去掉test url = url.replace(/\/test(?=\/)/g, ""); // 此时结果是 "https://www.google.es//hello/world" // 若需要合并连续的斜杠为单个,再执行一次替换 url = url.replace(/\/+/g, "/"); console.log(url); // 输出: "https://www.google.es/hello/world"
方案2:使用零宽前后断言精准替换斜杠间的test
如果只想替换被斜杠包裹的test(保留斜杠),可以用零宽前后断言匹配/test/中的test,替换为空:
let url = "https://www.google.es/test/test/hello/world"; url = url.replace(/(?<=\/)test(?=\/)/g, ""); console.log(url); // 输出: "https://www.google.es//hello/world"
方案3:单次匹配连续的/test/
如果确定只会出现连续的/test/,可以直接匹配多次重复的/test加上结尾的/,一次性替换成单个斜杠:
let url = "https://www.google.es/test/test/hello/world"; url = url.replace(/(?:\/test)+\//g, "/"); console.log(url); // 输出: "https://www.google.es/hello/world"
内容的提问来源于stack exchange,提问作者Meir
相关产品推荐
相关产品推荐

