我面临一个问题。我想用一个斜杠替换URL中的双斜杠或其他斜杠。但是我做错了。要求是斜杠应位于网址的中间或末尾,不应与协议(protocol)的双斜杠匹配,例如http://
和https://
。但是我的正则表达式也匹配这些斜杠。如何忽略协议(protocol)斜线?
const example1 = `https://example.com/home2`;
const example2 = `http://example.com/home2/`;
const example3 = `http://example.com//home2///`;
const example4 = `http://example.com/////home2///`;
const example5 = `http://example.com/////home2///heloo//////`;
const example6 = `http://example.com////home2/////////////`;
const example7 = `https://example.com////home2/////////////`;
const example8 = `http://localhost:9000/////`;
const patt = /\/\/+/g;
const res1 = patt.test(example1) ? example1.replace(patt, '/') : example1;
const res2 = patt.test(example2) ? example2.replace(patt, '/') : example2;
const res3 = patt.test(example3) ? example3.replace(patt, '/') : example3;
const res4 = patt.test(example4) ? example4.replace(patt, '/') : example4;
const res5 = patt.test(example5) ? example5.replace(patt, '/') : example5;
const res6 = patt.test(example6) ? example6.replace(patt, '/') : example6;
const res7 = patt.test(example7) ? example7.replace(patt, '/') : example7;
const res8 = patt.test(example8) ? example8.replace(patt, '/') : example8;
// The results should be something like this.
console.log(res1); // https://example.com/home2 => https://example.com/home2
console.log(res2); // http://example.com/home2/ => http://example.com/home2/
console.log(res3); // http://example.com//home2/// => http://example.com/home2/
console.log(res4); // http://example.com/////home2/// => http://example.com/home2/
console.log(res5); // http://example.com/////home2///heloo////// => http://example.com/home2/heloo/
console.log(res6); // http://example.com////home2///////////// => http://example.com/home2/
console.log(res7); // https://example.com////home2///////////// => https://example.com/home2/
console.log(res8); // http://localhost:9000///// => http://localhost:9000/
最佳答案
否定的lookbehind expression将起作用:(?<!:)\/\/+
从后方表达式允许您检查在其余比赛中处于领先地位的字符,而无需实际将其包括在比赛中。负向后检验表明那些前导字符不匹配。在这种情况下,(?<!:)
是后面的否定字符,可确保在表达式的其余部分之前没有冒号,但在最终匹配中不包含该前导字符。
关于javascript - 仅消除双斜线和其他斜线,并替换为一个斜线,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64951740/