Search code examples
javascriptrelative-pathfilepath

JS: Remove leading slashes, dots from relative path


Using Javascript how would I remove any number of "../" from a relative path?

For instance:

Before - '../../../folder1/folder2/my-file.php'
After  - 'folder1/folder2/my-file.php'

Before - '../folder1/my-file.php'
After  - 'folder1/my-file.php'

I've searched multiple keywords both here and at Google and can't seem to find a Javascript based solution, most are PHP which is not what I'm needing. Also, I'd like to avoid a regex solution if possible.

Any help would be appreciated, thanks!


Solution

  • Also, I'd like to avoid a regex solution if possible.

    In JavaScript, a regular expression is probably the best way to do this; but you could do it with a loop instead:

    var str = "../../../folder1/folder2/my-file.php";
    var result = str;
    while (result.substring(0, 3) === "../") {
        result = result.substring(3);
    }
    

    Using a regular expression and String#replace:

    var str = "../../../folder1/folder2/my-file.php";
    var result = str.replace(/^(?:\.\.\/)+/, "");
    

    That regular expression says: Match the start of the string (^) and then one or more ../ substrings, and replace them with "" (e.g., nothing). You need the backslashes in there because both . and / are special characters in regular expression literals, but we want them to actually be . and / in your string. The (?:___) construct groups those three characters together without forming a capture group.

    More on regular expressions on MDC or (much, much less clearly) in the specification.