How to replace double / multiple slash with single slash in url

I have a url: http://127.0.0.1:7000//test//test//index.html

Expected Result: http://127.0.0.1:7000/test/test/index.html

I use this regex: [^http:](\/{2,})

and output: http://127.0.0.1:700/test/test/index.html

matches: '0 //' '//'

here is a demo: https://www.debuggex.com/r/dXZouvlec4srhg8i

where am i wrong

+4
source share
3 answers

you can use

var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2");

Watch the regex demo

More details

  • (https?:\/\/)- captures http://or https://in group 1
  • | - or
  • (\/)+- one or more slashes match, and only one is /stored in group 2

$1 1 ( ), backreference $2 .

var s = "http://www.gogogogo.com//something//here";
var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2");
console.log(res);
Hide result
+3
var = 'http://127.0.0.1:7000//test//test//index.html';
str.replace(/([^:])(\/{2,})/g,"$1/");

: http://127.0.0.1:7000/test/test/index.html '.

'[^ http:]' , h t p:, 4 .

+1

, , - Regexp:

https://regex101.com/

, [^] ^ []. [] , A-Z, a-z, 0-9, A-z ..... [^] , .

, : , , h, t, p, :, /

The results are 0 // for full compliance, and // for member () in the same place. The other // s is preceded by either: or t, and therefore not consistent.

0
source

Source: https://habr.com/ru/post/1661025/


All Articles