0

I have a file url and I need to slice it for showing the file to the users. I have successfully sliced it using substring but what if the string to slice isn't fixed. Like this /media/users/3/sample.docx. I wanted to show sample.docx only so I used substring but what if the numbers before that, increases like the number 3? How can do it the better way?

sliceString(value) {
   return value.substring(15)
}

{{sliceString(data.file)}}

5 Answers 5

2

Take the last index of /, add 1 to it and use in the substring method :

sliceString(value) {
    let lastSlashIndex=value.lastIndexOf('/')
    return value.substring(lastSlashIndex+1)
}

Example:

let url = 'sample.com/media/users/3/sample.docx'

let lastIndex= url.lastIndexOf('/');

console.log(url.substring(lastIndex+1))

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

Comments

0

Try to use value.lastIndexOf()

 sliceString(value) {
     return value.substring(value.lastIndexOf("/")+1)
 }

 {{sliceString(data.file)}}

Comments

0

Try using split:

const url = 'sample.com/media/users/3/sample.docx';
url = url.split('/');
len = url.length;
const sample = url[len-1];
console.log(sample) // 'sample.docx'

4 Comments

This solution isn't generic. what if url = 'sample.com/media/users/4/3/sample.docx'?
It's generic for a certain purpose but not dynamic, good point. WIth the solution you provided is it possible to get something else than the last index? For example if the user would want to get the the content after the first slash.
if the user would want to get the the content after the first slash: value.substring(url.indexOf("/"))
Instead of using the index, use return url.pop();
0

You can use regex to do it like that

const url = 'sample.com/media/users/3/sample.docx'

console.log(url.match(/[^\/]+$/)[0])

Comments

0

This should shrink the URL to just the filename even if there are query string parameters :

const fileString = 'file:///folder1/folder2/folder3/filename.extension?possibleQueries';
sliceURL = ((url) => {
    lastChar = url.length;
    if (url.lastIndexOf('?') > -1) {
        lastChar = url.lastIndexOf('?');
    };
    return (url.substring(url.lastIndexOf("/") + 1, lastChar));
})
(fileString); // Expected output: "filename.extension"

Comments

Your Answer

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