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?