Search code examples
javascriptjqueryregexurlslash

Remove slashes from Start and end of the URL


I have a URL like :

var folderPath = 'files/New folder';

Here are the conditions that i want to prevent, For example user tries:

../../.././../../././../files/New folder

OR

../../.././../../././../files/New folder/../../././../.././

OR

./files/New folder/

Basically i need to extract the New folder from the URL thus i need the URL cleaned !

WHAT I HAVE TRIED?

Tried the following but it only removes the Multiple slashes '../' and './' from the start of the URL.

var cleaned  = folderPath.replace(/^.+\.\//, '');

EXPECTED OUTPUT: if someone can provide a function that cleans the url that will be much helpful.

files/New folder

Solution

  • How about a filter?

    var oneSlash = (str) => str.split("/").filter(
          word => word.match(/\w+/)
        ).join("/")
    
    console.log(oneSlash(" ../../.././../../././../files/New folder"))
    
    console.log(oneSlash("///../..///files/New folder///../"))
    
    // this imaginary useless path ends up like the others
    
    console.log(oneSlash("files/////New folder/"))