Obtaining the base name of all subpaths within a given string

I'm fairly new to working with Vue and JS. Let's consider an array of objects where each object contains a "name" field, representing various processes or commands. For instance:

/disks/tools/itools/odor/src/bin/lib/script.py -path /disks/tools/itools/ps/char/leno/tool/src/work/dir -i ./report/dir/bin/a -report -id 12345 --name my_/name

I have written a piece of code that takes this array, iterates through it, and creates a shorter version for each entry. Using the example above, the output would be:

script.py -path dir -i a -report -id 12345 --name my_/name

The goal is to shorten any substring containing a "path". To achieve this, I check if the first symbol of the substring is either / or ./, and then extract the basename.

Here's the code snippet I've implemented:

addShort: function(arr) {
    for (var i of arr) {
        if (i.name) {
            i.fullname = i.name;
            i.name = '';
            var splitedArr = i.fullname.split(' ');
            for (var path of splitedArr) {
                i.name += this.basename(path);
            }
        }
    }
},

basename: function(str) {
    var nStr = str.replace(/^.*[\\\/]/, '');
    return newStr | '';
}

As a beginner in Vue and JS, I have some doubts about the quality of this code. I believe it can be optimized for better clarity and efficiency. Additionally, I am unsure if my regular expression covers all necessary cases. Moreover, I noticed that each string has an extra space at the end, prompting me to revise the basename function as follows:

basename: function(str) {
    var nStr = str.replace(/^.*[\\\/]/, '');
    return newStr | '';
}

I also considered adding a space to the line i.name += this.basename(path); like so:

i.name += this.basename(path).' ';
. However, this approach retains the trailing space. Is there a way to determine the last iteration of the loop so I can avoid adding the extra space?

Please forgive me for taking up your time with my uncertainties.

Answer №1

Below is a more concise method:

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

Another way to shorten the basename function is:

basename(str) {
  // This will get the basename of strings that start with / or ./
  return str.replace(/^\.?\/.*[\\\/]/, '');
}

I believe we can cover all scenarios by examining the first symbol of the substring - if it's / or ./, then we should extract the basename.

Note that relative paths may look like this:

path/to/file.txt

Also, be cautious not to create the i.fullname property (it should already be present in the i object) as it might not update dynamically (if displayed in the template).

Answer №2

When venturing into unfamiliar territory, I find peace of mind through unit testing. Implementing simple unit tests can help verify that the functions you've created are performing as expected. There are excellent unit testing frameworks for JavaScript such as Jest and Jasmine.

If you're struggling with getting your regular expressions to work across all cases, I highly recommend using this regex site. It offers a convenient reference panel in the bottom left corner that outlines the available regex character options.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having an issue with both of my states being called simultaneously, resulting in a TypeError: Cannot read property 'map' of undefined

I am facing an issue with displaying both of my states on localhost (I am receiving the following error message: TypeError: Cannot read property 'map' of undefined). Skills.js import React, { Component } from 'react'; import ProgressBa ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

Issue with event delegation when using if-else conditions is not being resolved

I have set up an event listener on an HTML container, and when the user clicks on the play again button, the code inside the 'if' statement should be executed. However, nothing happens when clicking on the play again button and no logs are output ...

The mongoose find query is coming back with an empty array, even though there is data present in the

My goal is to update commodity data in my stockrecord collection by adding the quantity of a commodity if it already exists in the collection. However, I encountered an issue where the find method returns an empty array even for existing data. Here is th ...

What is the proper method for incorporating a Greater-than symbol within a jsx tag?

I am attempting to display a Greater-than sign '>' inside of a button using material-ui with react, but I am receiving a parsing error. Is there a simpler way to achieve this without writing lengthy code? <Button onClick={includeOperator(& ...

evaluating an object against null

When comparing two objects a and b, it is necessary to ensure that one of them is not null. However, deciphering this can be quite chaotic. {} - null => -0 [] - null => 0 1 - null => 1 "1" - null => 1 true - null ...

Verify the validation of the text box

Checking a textbox control for validation is necessary. Validation Criteria: Value should be between 0 and 1000, with up to 2 decimal places (e.g. 1.00, 85.23, 1000.00). Once 2 decimal points are used, users should not be able to enter additional ze ...

Generate your own unique referral links today

Searching for ways to generate and monitor referral links like www.domain.com/?ref=switz What steps should I take to accomplish this? ...

Utilizing Angular: Integrating the Http response output into a map

I have a situation where I am making multiple HTTP calls simultaneously from my Angular application. The goal is to store the responses of these calls in a Map. data: Map<number, any> = new map<number,any>(); --------------------------------- ...

There seems to be an issue with the Redux connect() higher order component not functioning properly when passing an action creator and

Encountering an issue with the Action creator in react-redux when using the mapDispatchToProps function to return an object to pass into the connect HOC. The strange thing is that it works fine when passing the Action creator directly into the connect HOC, ...

Variables in a Docker file specific to VueJS

I am faced with a situation where I have a configuration file located at "src/config.js" that contains the API URL: const API_URL = 'https://some-url-here.com' export default { API_URL: API_URL } In addition, there is a Dockerfile setup as f ...

When using vue-resource for an http request, the error message "_.isArray is not a function" may be

Attempting to retrieve an object from a server located at localhost:3000. The object is visible when accessing the address via a web browser. In my Vue instance's methods property, I have a function that is executed on the front end: goToTutors: fun ...

Code containing insertAdjacentHTML() does not run as expected due to injection of script

I have a scenario in my application where I am sending a request from the client to a node.js server. The server responds with an HTML containing a script: app.post('/verify', cors(issue2options), async (req, res) => { let auth = await mon ...

next.js retrieves information from Laravel

As part of my Laravel project, I have written a simple user registration feature with the following code: public function register() { $this->validate(request(), [ 'name' => 'required', 'email' => ...

Encountered an issue while implementing the post function in the REST API

Every time I attempt to utilize the post function for my express rest API, I encounter errors like the following. events.js:85 throw er; // Unhandled 'error' event ^ error: column "newuser" does not exist at Connection.parseE (/Use ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

Efficient Pagination with React Redux

Case One: I am currently implementing server-side pagination in Rails using React for the front-end and Redux for state management. I have completed all the necessary setup, and the only thing left is to pass the newly generated URL to fetch the new data. ...

What is the best way to create a Div element that functions as a button, becoming active when clicked while deactivating all other Div elements

function toggleButton1() { $("#button1").toggleClass("button-active button-inactive"); $("#button2").toggleClass("button-inactive button-active"); $("#button3").toggleClass("button-inactive button-active"); } function toggleButton2() { $("#butto ...

manipulating session variables with javascript ajax and php

I'm struggling with setting and retrieving session variables using JavaScript code that calls PHP functions via AJAX. I want to access the returned session field in my JavaScript, but nothing seems to be working. Can someone take a look at my code and ...

Angular Resolve Upon Application Reloading

Is there a way to postpone the initialization of my Application Controller (similar to using the 'resolve' attribute in the router) when reloading a page? Or more importantly, how can I delay the rendering of the view until my controller has succ ...