Alexander
Alexander

Reputation: 20234

Javascript replace() regexp: nesting modifier

I have a concatenated file path to a document on a server, e.g.

http://test:[email protected]:5555/../test/directory/../name/sub/sub/../../file.js

and for some unknown reason the XHR request I send out to that "URL" returns error 404, while Chrome, when I give him the same path, makes

http://test:[email protected]:5555/test/name/file.js

from it and returns the document okay. Now I am searching for a javascript regexp search/replace that can "clean" the path.

This is what I have tried so far:

console.log(
    "http://test:[email protected]:5555/../test/directory/../name/sub/sub/../../file.js"
    .replace(/([^\/])\/[^\/]*\/..\//g,'$1/')
);

The regexp works except for nested matches: /sub/dir/../../ is replaced to /sub/../, should be /.

Is there a nesting modifier available?

Upvotes: 2

Views: 85

Answers (1)

user4227915
user4227915

Reputation:

You can try this approach:

var url = "http://test:[email protected]:5555/../test/directory/../name/sub/sub/../../file.js";

var new_url = url.replace(/(^.*?(?=\/\.\.))|(?:\/\.\.)+(\/[^\/]+)|./g, '$1$2');

document.write(new_url);

Regex with colors here.

Hope it helps.

Upvotes: 2

Related Questions