Regex: Fix duplicate slashes without affecting protocol

mattkenefick

Matt Kenefick

Posted on May 13, 2021

Regex: Fix duplicate slashes without affecting protocol

Let’s say you want to fix a URL that looks like:

https://www.example.com/my/path//to-file.jpg
Enter fullscreen mode Exit fullscreen mode

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.

(?<!:)/+
Enter fullscreen mode Exit fullscreen mode

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"
```

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
mattkenefick
Matt Kenefick

Posted on May 13, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related