Let’s say you want to fix a URL that looks like:
https://www.example.com/my/path//to-file.jpg
Using a string replace or a simple regex could incorrectly “fix” the double slashes following the protocol. We can fix that by using a negative lookbehind.
(?<!:)/+
For PHP:
<?php
$url = 'https://www.example.com/my/path//to-file.jpg';
$str = preg_replace('#(?<!:)/+#im', '/', $url);
// https://www.example.com/my/path/to-file.jpg
For Javascript:
let url = 'https://www.example.com/my/path//to-file.jpg';
url.replaceAll(/(?<!:)\/+/gm, '/');
// "https://www.example.com/my/path/to-file.jpg"
Print
Share
Comment
Cite
Upload
Translate
APA
Matt Kenefick | Sciencx (2024-03-29T11:54:53+00:00) » Regex: Fix duplicate slashes without affecting protocol. Retrieved from https://www.scien.cx/2021/05/13/regex-fix-duplicate-slashes-without-affecting-protocol/.
MLA" » Regex: Fix duplicate slashes without affecting protocol." Matt Kenefick | Sciencx - Thursday May 13, 2021, https://www.scien.cx/2021/05/13/regex-fix-duplicate-slashes-without-affecting-protocol/
HARVARDMatt Kenefick | Sciencx Thursday May 13, 2021 » Regex: Fix duplicate slashes without affecting protocol., viewed 2024-03-29T11:54:53+00:00,<https://www.scien.cx/2021/05/13/regex-fix-duplicate-slashes-without-affecting-protocol/>
VANCOUVERMatt Kenefick | Sciencx - » Regex: Fix duplicate slashes without affecting protocol. [Internet]. [Accessed 2024-03-29T11:54:53+00:00]. Available from: https://www.scien.cx/2021/05/13/regex-fix-duplicate-slashes-without-affecting-protocol/
CHICAGO" » Regex: Fix duplicate slashes without affecting protocol." Matt Kenefick | Sciencx - Accessed 2024-03-29T11:54:53+00:00. https://www.scien.cx/2021/05/13/regex-fix-duplicate-slashes-without-affecting-protocol/
IEEE" » Regex: Fix duplicate slashes without affecting protocol." Matt Kenefick | Sciencx [Online]. Available: https://www.scien.cx/2021/05/13/regex-fix-duplicate-slashes-without-affecting-protocol/. [Accessed: 2024-03-29T11:54:53+00:00]
rf:citation » Regex: Fix duplicate slashes without affecting protocol | Matt Kenefick | Sciencx | https://www.scien.cx/2021/05/13/regex-fix-duplicate-slashes-without-affecting-protocol/ | 2024-03-29T11:54:53+00:00
https://github.com/addpipe/simple-recorderjs-demo