Home > Software engineering >  Remove part of string using regex and replace
Remove part of string using regex and replace

Time:12-04

give a string like this (it can be any pattern, but the following format):

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

I am making a function that, when I pass some address parts, the function will return those parts and remove extras part that are not requested and mantaining maximum one spacing _ if many where removed:

FE :

exs :

 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"

Now, My method is as follow :

  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;
  }

the above looks ok, but it fail at the end and start :

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

How can I remove /_/ or _/ if it is situated on start or at the end without relooping over the array ?

CodePudding user response:

You can use regexes on the final string to remove leading and trailing unwanted symbols

The first regex looks for:

  • Start of the string, with the ^ symbol

  • One or more "_/", using

    parentheses to group the character pair,

    the sign to allow 1 or more, and

    a backslash to escape the forward slash

And the second regex looks for:

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

s1 = "_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/"
s2 = s1.replace(/^(_\/) /,"").replace(/\/(_\/)*$/,"")
console.log(s2)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You may be able to simplify

If you know for certain that there will no more than one "_" at the beginning and one at the end, you don't need the parentheses and /* symbols.

  • Related