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!
In JavaScript, a regular expression is probably the best way to do this; but you could do it with a loop instead:
Using a regular expression and
String#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.