Using regular expressions, you can eliminate a specific segment of a string and substitute

Provide a string in the following format:

lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone

I am creating a function that will extract the specified address parts and remove any extra parts while maintaining maximum one space _ if multiple spaces are removed:

For example:

Input:

 input : ["country", "postalCode"]
 return "country/postalCode"
 input : ["lastname", "firstname", "regionId"]
 return "lastname/firstname/_/regionId"
 input : ["firstname", "country", "regionId", "city"]
 return "firstname/_/country/_/regionId/city"
 input : ["country", "regionId", "phone"]
 return "country/_/regionId/_/phone"

Here is how my method works:

  type AddressPart = "firstname" | "lastname" | ... | "phone";
  const allAddressParts = ["firstname", "lastname", ..., "phone"];
  static getAddress(
    format = "lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone",
    parts: AddressPart[],
  ) {
    const toRemove = allAddressParts.filter((part) => !parts.includes(part));
    toRemove.forEach((part) => {
      format = format
        .replace(`_/${part}/_`, '_')
        .replace(new RegExp(part + '/?'), '');
    });
    return format;
  }

Although the above method works, it fails at the start and end:

_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/

Is there a way to remove /_/ or _/ if it is at the beginning or end without re-looping through the array?

Answer №1

To eliminate unwanted symbols, consider using regex patterns on the final string

The initial regex pattern seeks:

  • The start of the string, indicated by the ^ symbol

  • One or more instances of "_/," enclosed in parentheses to group the characters, the + sign to allow for 1 or more occurrences, and a backslash to escape the forward slash

The secondary regex pattern detects:

  • a "slash"
  • zero or more "_/," denoted by the *
  • the end of the string with the $ symbol

s1 = "_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/"
s2 = s1.replace(/^(_\/)+/,"").replace(/\/(_\/)*$/,"")
console.log(s2)

Simplification may be possible

If you are certain that there will only be one "underscore" at the start and end, you can skip the parentheses and +/* symbols in your regex pattern.

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

Received an unexpected character '?' in NextJS

After setting up a fresh installation of Ubuntu 22.04.1 LTS and installing npm and docker, I encountered an issue while trying to start my NextJS web server with the command npm run dev. An error message appeared as follows: niklas@srv-code01:~/Desktop/Co ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...

What is the best approach to implementing a 30-minute expiration for a JWT token?

I'm having trouble setting the expiration time for my jwt token to 1 minute in my code. How can I resolve this issue? It seems a bit confusing...I want the token to expire after 1 minute. (auth.js) const express = require("express"); const p ...

Performing a Javascript validation to ensure that a value falls within

How can I check if an input number falls within a specified range? I need to display if it is within the range, higher, or lower than the acceptable range. My current Javascript code seems to be causing an error message stating it is an invalid entry. It ...

Node scripts and node bins are causing errors in Vue.js when running npm

While attempting to run my Vue project with the command npm run serve I encountered an error message that read: [email protected] serve /home/numan/Desktop/vue-getting-started/07-accessing-data/begin/vue-heroes vue-cli-service serve sh: 1: vue- ...

When utilizing MUI's ThemeProvider, it may result in encountering errors that display as "undefined"

I am facing an issue with my MUI application. Everything was working perfectly until I decided to implement a ThemeProvider. It seems that as soon as I add the ThemeProvider, the application breaks and all MUI components I'm using start throwing undef ...

When using ng-repeat in Angular.js, an additional td is created

https://jsfiddle.net/gdrkftwm/ https://i.sstatic.net/CTi2F.jpg I have encountered a problem while creating a table from a Json object. There seems to be an extra td being generated, and I'm not sure why. I want the structure of my table to resemble ...

Is it possible to utilize an XML format for translation files instead of JSON in React Native?

I'm in the process of creating a react native application using the react i18next library. For translations, I've utilized XML format in android for native development. In react native, is it possible to use XML format for translation files inste ...

I am wondering how to use the value assigned to a variable's textContent as an argument for player input in my JavaScript code

i am currently developing a JavaScript project to create a user interface for my rock, paper, scissors game. Currently, the game only runs in the console and prompts the player for input. So far, I have implemented three buttons (one each for rock, paper, ...

Console frozen when executing an async JavaScript script to populate a Mongoose database

I'm currently delving into a personal project and aiming to unravel the intricate logic that is preventing my Node JS process from closing after executing populateTransactions(). My assumption is that the issue lies in not properly closing the DB con ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Will adding additional line breaks increase the overall length of the code?

Currently, I am immersed in a project involving Angular 4 and TypeScript. Recently, I came across a video showcasing how VSCODE can enhance the code's appearance. Intrigued, I installed the prettier plugin to achieve the same effect. Running this tool ...

The index type 'X' is not allowed for use in this scenario

I encountered an issue in my TypeScript code: error message: 'Type 'TransitionStyles' cannot be used as an index type.' I'm wondering if there's a way to modify my interface so that it can be used as an index type as well: ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

Configuring webpack for live reloading and Hot Module Replacement on static pages

The title of this post may not be very clear, but I appreciate your patience. I am currently in the process of setting up React for an older Rails application that uses static ERBs. Due to the size of the project, I am gradually transitioning towards a Si ...

Encountering a problem with scrolling the modal to the top

I am currently working on a code snippet that involves scrolling the modal to the top position. The purpose of this is to display form validation messages within the modal popup. Below are the jQuery code snippets that I have attempted: //Click event t ...

Instructions for extracting and storing values from a JSON response into an array

Utilizing react-select async feature to fetch options from an input provided via an API. The JSON response contains a list with a "FullName" field, which I aim to extract and store in an array to be used as options. Within the JSON structure, there is a l ...

Unveiling the secrets of the Google Region Lookup API

I am struggling to incorporate the Region Area Lookup feature from Google Maps into my project. Despite it being an experimental feature, I am having difficulty getting it to function correctly. Initially, I attempted to integrate this feature into a Reac ...

How can Karma unit tests with Jasmine in a TypeScript Node project accurately measure code coverage, even with external dependencies?

We have a unique situation with the code coverage of our project involving a node dependency. It's important to note that the npm dependency source code is actually part of our project, as we are responsible for its development and publication. Here&a ...