What is the most effective method for eliminating leading and trailing slashes from a string - if they are present - while preserving the middle ones in TypeScript/JavaScript?

I have come across these variations of strings:

some/dir/with/end/slash/
/some/dir/with/start/slash
some/dir/without/any/start/or/end/slash
/some/dir/with/both/slashes/

My goal is to remove both the start and end slashes if they exist, while keeping the middle ones intact, all in a single operation.

Is there a way to achieve this in one go?

I am currently utilizing NodeJS along with TypeScript for this task.

The expected output should be:

some/dir/with/end/slash
some/dir/with/start/slash
some/dir/without/any/start/or/end/slash
some/dir/with/both/slashes

Answer №1

To remove slashes from the beginning and end of a string, you can use the replace method with the following pattern:

`^\/|\/$` 
  • ^ - Anchors to the start of the string
  • \/ - Matches a forward slash
  • $ - End of the string

let arr = [`some/dir/with/end/slash/`,`/some/dir/with/start/slash`,`some/dir/without/any/start/or/end/slash`,`/some/dir/with/both/slashes/`]

arr.forEach(e=>{
  let str = e.replace(/^\/|\/$/g, '')
  console.log(str)
})

Alternates

  1. Using a simple for loop

let arr = [`some/dir/with/end/slash/`,`/some/dir/with/start/slash`,`some/dir/without/any/start/or/end/slash`,`/some/dir/with/both/slashes/`]

arr.forEach(e=>{
  let str = ''
  for(let i=0; i<e.length; i++){
    if((i === 0 || i === e.length-1) && e[i] ==='/'){
      continue
    } else {
      str += e[i]
    }
   }
  console.log(str)
})

  1. Using startsWith and endsWith

let arr = [`some/dir/with/end/slash/`,`/some/dir/with/start/slash`,`some/dir/without/any/start/or/end/slash`,`/some/dir/with/both/slashes/`]

arr.forEach(e=>{
  let str = e
  if(e.startsWith('/')){
    str = str.substring(1,)
  }
  if(e.endsWith('/')){
    str = str.substring(0,str.length-1)
  }
  console.log(str)
})

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

What is the method to make a String bold when sending it through a messaging service?

Here is the structure of my service: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MessageService { messages: string[] = []; add(message: string) { this.messages.push(message); ...

Having trouble selecting checkboxes in React Native

When working on React Native tests, I utilize react-native-paper. Below is the code snippet: {(!props.question.isSingleAnswer && props.question.answers.length) && <View> {props.question.answers.map((item) => ( ...

Harnessing the Power of Webpack, TypeScript, and Sequelize: A Comprehensive Guide

After revising my query, I'm still encountering the same issue. The technologies I am utilizing include webpack, TypeScript, and Sequelize. My aim is to integrate Sequelize into a TypeScript backend file. I have successfully installed Sequelize and ...

N8N: Deleting JSON Key from Output

Is it possible to remove the json key in my output file? I am unsure of the best approach to achieve this. I would like to return an array of data with all values, not just one value. If you want more information, here is a link to my N8N post: Manipulate ...

retrieve essential data from Firebase using JavaScript

Currently, I am utilizing the get() method to retrieve data in my React Native application. Here is the code snippet that I am using: firebase .firestore() .collection("users") .doc("test") .get() .then(response => { console.log(respo ...

IntelliJ does not provide alerts for return type inconsistencies in TypeScript

During the development of our web application using react+typescript+spring boot with IntelliJ, everything seemed to be going smoothly until I came across an unexpected issue. Take a look at this code snippet example: export class TreeRefreshOutcome { } e ...

Is the NodeJS rmdir function experiencing issues specific to LINUX?

Currently, I have a NodeJS script section that runs on my Windows 10 machine with the latest Node version and another version on my CentOS8 Linux webserver. The code executes as expected on Windows but throws an error when running on Linux at this specific ...

Using JQuery to verify if a certain letter or word has been entered by the user in a textarea

Can anyone assist me in checking if a user has entered a specific letter or word and, if correct, display a button? I would appreciate any guidance! Here is my current code snippet: $(document).ready(function() { $(".textArea").keyup(function() { ...

Angular 2.0 encountered an unexpected value from the module 'AppModule' which appears to be an '[object Object]'

Every time I attempt to load my angular version 2.0 application, I encounter the following error: (index):21 Error: Error: Unexpected value '[object Object]' imported by the module 'AppModule' import { ModuleWithProviders } from ' ...

What is the best way to show a spinner or progress bar while loading an image?

I'm currently developing a React app using Next.js to display various images. The user can click on an item from the list on the left, which then displays three images on the right. These images are rendered using the Next.js Image component: ...

How can a TypeScript Type be handed over as a prop to a React component?

Can you pass a TypeScript type as a property to a React Component? export type ActivitiesType = { RUN: "RUN"; WALK: "REST"; ROUNDS: "ROUNDS"; }; <MyComponent activity={ActivitiesType.RUN} /> Next, in MyComponent: const MyComponent = ({ act ...

Setting default values on DTO in NestJS can be done by using the DefaultValue decorator provided

import { IsString, IsNumber, IsOptional, IsUUID, Min, Max } from 'class-validator'; import { Transform } from 'class-transformer'; export class QueryCollateralTypeDto { @Transform(({ value }) => parseInt(value)) @IsNumber() @I ...

Navigating URL to switch data access

Is there a way to toggle the visibility of a div when I add #ID at the end of the URL? For instance, if I access a URL like domain.com/xxxxxx#01, then the specified div should be displayed. $(document).ready(function() { $(".toogle_button_<?php echo ...

Adjusting Chrome Zoom to 100% with Selenium in C#

I've been trying to use this code in Selenium with C# to adjust the zoom level of the Chrome browser to 100% using JavaScript. However, it doesn't seem to be working as expected. Can someone please assist me with this issue? var js = ((IJavaScri ...

Can you explain the distinction between these codes?

function Example() { this.display1 = function() { alert(1) } } Example.prototype.display2 = function() { alert(2) } var e = new Example e.display1() e.display2() display1 and display2 both have the ability to trigger an alert showing a number. Do yo ...

Error: The function updateElement does not exist

Currently, I am facing an issue while trying to update an element in an array by adding an object as a property. This requires user interaction through a modal where the form is filled and then added as a property for a specific node. However, I encountere ...

Is it possible to send multiple HTML input values to a Google Spreadsheet using only JavaScript?

Seeking a faster and more efficient way to send the values of multiple HTML Inputs to a specific location in a Google Spreadsheet? The existing script takes too long to complete, often skips inputs, and relies heavily on "google.script.run". Due to softwar ...

Steps For Adding Margins To A ProgressBar In Bootstrap To Give It A Spaced Look

Currently, I am endeavoring to design a progress bar that includes some spacing from the edges. The desired end result can be seen in the image below: https://i.sstatic.net/IvMFS.png The visual displays a red line within the gray progress bar, which is e ...

Form a hierarchical data structure using a combination of three arrays

Here are three sets of data: let firstData = [ {key: value1}, {key: value2}, {key:value3} ] let secondData = [ {key: value1}, {key: value2}, {key:value3}, {key: value4} ] //same structure, different values let thirdData = [ [1,1,1,1], [1,1,1,1], [1,1,1,1] ...

There is no 'Access-Control-Allow-Origin' header found on the requested resource in Heroku for Node.js

Here is the header setup in my Node.js API app: res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested, Content-Type, Accept Authorization" ); ...