[Vuejs]-Getting the basename of each subpath in a string

0👍

Here’s a shorter way:

i.name = i.fullname
  .split(/\s+/)
  .map(arg => this.basename(arg))
  .join(' ');

Also the basename function can just be shortened to:

basename(str) {
  // Will take the basename of strings that start in a / or ./ only
  return str.replace(/^\.?\/.*[\\\/]/, '');
}

I think that we can catch all of the cases by looking at the first symbol of the substring – if it’s / or ./ then we should take the basename

Keep in mind relative paths can be like this too:

path/to/file.txt

Also be careful that you’re not creating the i.fullname property (it should already exist in the i object) otherwise it won’t be reactive (if you’re rendering it in the template).

-1👍

I’d like to add in that unit testing is the main way I put myself at ease when I’m working in new territory. Throw in some simple unit tests, it doesn’t have to be anything fancy that will help you say definitively that the functions you wrote work as expected. There are several phenomenal unit testing frameworks for js (i.e. Jest or Jasmine).

In addition, if you are having some difficulty getting your regex to work for every case, I’d recommend this regex site because of its quick reference panel in the bottom left that describes exactly what regex character options you can choose from.

Leave a comment