31

How can I remove duplicate forward slashes from the a url, but keep the // which comes after http: so that the URL does not break.

http://localhost//example/author/admin///

should be

http://localhost/example/author/admin/

I'm trying this, but it will remove only the last slash. I want to remove all double

abc = 'http://localhost//example/author/admin///';
clean_url = abc.replace(/\/$/,'');
alert(clean_url);

The following checks only three slashes.

clean_url = abc.replace("///", "");
alert(clean_url);

I want to remove all the duplicate slashes.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
user3761459
  • 519
  • 2
  • 5
  • 10
  • 1
    I would better work on the URL generation so that one slash cannot follow another one. How are these URLs generated? – sp00m Jun 24 '14 at 08:14
  • 3
    I would fix it at the source - why are these duplicate slashes in the URL to begin with? – Rory McCrossan Jun 24 '14 at 08:14
  • I understand but its quite a long story. I'm trying to use pagination within the tabs. So when you are on a paginated link like something/music/page/6 and you click on other tab, then go to the other page, the URL still have the /page/6 from previous tab, so I need to remove the paginated part from the url when switching the tabs. Hope it makes sense. – user3761459 Jun 24 '14 at 08:19
  • Removing multiple forward slashes generally breaks the URL - the new url is not the same as the old one. – Remember Monica Jun 20 '22 at 10:39

5 Answers5

67

You can use:

abc.replace(/([^:]\/)\/+/g, "$1");

Working Demo

Update: Already answered by Halcyon

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
9

This question has been answered before...

var str = 'http://localhost//example/author/admin///';    
var clean_url = str.replace(/([^:])(\/\/+)/g, '$1/');

alert(clean_url);

DEMO

Community
  • 1
  • 1
martynas
  • 12,120
  • 3
  • 55
  • 60
4

I know there're different answers solving the same problem, just another approach :)

var s = "http://www.some-url.com//path//to";
var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2");
Burak Tasci
  • 887
  • 12
  • 18
0

Thanks @Milind Anantwar

I use the following in my Lambda@edge viewer rule to fix duplicate slashes in URL.

'use strict';
exports.handler = (event, context, callback) => {

    // Get request from CloudFront event
    var request = event.Records[0].cf.request;

    // Extract the URI from the request
    var requestUrl = request.uri;

    // Match any duplicate double slashes in URL 
    var redirectUrl = requestUrl.replace(/([^:]\/)\/+/g, "$1");

    // Replace the received URI with the URI that includes the index page
    request.uri = redirectUrl;

    // Return to CloudFront
    return callback(null, request);
};
-1

PHP: To remove extra forward slashes, the below code works fine for me

$path = preg_replace('#/+#', '/', $path);

Ali
  • 49
  • 4