An Interest In:
Web News this Week
- May 1, 2024
- April 30, 2024
- April 29, 2024
- April 28, 2024
- April 27, 2024
- April 26, 2024
- April 25, 2024
May 13, 2021 03:34 pm GMT
Original Link: https://dev.to/mattkenefick/regex-fix-duplicate-slashes-without-affecting-protocol-2dbl
Regex: Fix duplicate slashes without affecting protocol
Lets 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"
Original Link: https://dev.to/mattkenefick/regex-fix-duplicate-slashes-without-affecting-protocol-2dbl
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To