1

I have this link/string:

https://link/to/a/file/filename.ext

My JS skills are now rusty and I need to trim the link from the last instance of / so that I could separate the directory and the file name (with the file extension attached to the file name).

var string = 'https://link/to/a/file/filename.ext';

var directory = 'https://link/to/a/file/'; // should have a value of 'https://link/to/a/file' coming from var string
var file = 'filename.ext'; // should have a value of 'filename.ext' coming from var string

3 Answers 3

3

You can use split() and join()

var string = 'https://link/to/a/file/filename.ext';
const strArray = string.split('/');
var file = strArray.pop();;
var directory = strArray.join('/');

console.log(file, directory);

Sign up to request clarification or add additional context in comments.

Comments

1
var string = 'https://link/to/a/file/filename.ext';     
directory = string.substring(0, string.lastIndexOf("/"));
console.log(directory);
file = string.substr(string.lastIndexOf("/")+1);
console.log(file);

1 Comment

Thank you for this. I kinda expect that more variation of these answers would pop up in this question
1

/ In the search parameters

The other solutions split the whole url at the last /, but in practice you can have situations where the search parameters contain a /. For example, a redirect parameter for a single sign on.

The example below uses the URL object to parse the URL first so that you don't have to mess with that, then uses just the path name to get the parts you want:

//Based on a real SSO url
var u = new URL('https://idp.blarg.edu/made/up/url/file.ext?service=https://some.webservice.blarg.edu/some/thing/on/the/internet.net?FolderPath=thingy.CO_EMPLOYEE_SELF_SERVICE.BLARG%26IsFolder=false%26IgnoreParamTempl=FolderPath%2cIsFolder%26');

// Split the path only on the last /, (no url params)
// I like a regex here cause it splits exactly into 2, but split() may be more readable...
[_, path, file] = u.pathname.match('^(.*)/([^/]*)$');

console.log(u.origin + path);
console.log(file);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.