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 ?
string.replace(/^_\/$/, '')