DEV Community

Manav Misra
Manav Misra

Posted on

Split Path String

// 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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)