// TODO: Split this long path up to get 2 strings - one for 'file' and one for the 'directory' π
const longPath = '/placeholder/default/photo-coming-soon.jpg'
String.prototype.split()
This method will split up a string into an array. It takes an optional parameter to specify a specific 'string' to 'split at.'
Given longPath
ππ½: const pathStrSplit = longPath.split("/")
will give pathStrSplit
a value of: [ '', 'placeholder', 'default', 'photo-coming-soon.jpg' ]
.
This is nothing but the original string turned into an array by splitting at each "/"
occurrence. This consequently also removes "/"
, which is fine.
You might also notice that we have an empty string at the 'position 0
' - this is from the first 'split' at the first "/"
. π
Get the File String
We see that the last index of the array ππ½ is what we need for the file name string.
Given pathStrSplit
ππ½: const fileName = pathStrSplit.pop()
will remove that last element from the array and give it to us.
This will mutate the original array referenced by pathStrSplit
. So, it's current value is nothing but: [ '', 'placeholder', 'default' ]
Now, 'file name string' is dun! β
Get the Directory Path String
Now, the opposite of split(/)
that we did earlier is nothing but join(/)
. This will 'join' our array elements into 1 string with /
as the 'glue,' if you will.
So, again, using pathStrSplit
ππ½: const directoryName = pathStrSplit.join("/");
will give to us: /placeholder/default
All Together Now
// TODO: Split this long path up to get 2 strings - one for 'file' and one for the 'directory' π
const longPath = '/placeholder/default/photo-coming-soon.jpg'
const pathStrSplit = longPath.split('/')
const fileName = pathStrSplit.pop()
const directoryName = pathStrSplit.join('/')
console.log(fileName, directoryName) // photo-coming-soon.jpg /placeholder/default
Top comments (0)