I wanted to output the following based on regex expressions. I wanted to have some kind of reusability based on filename formats
Filename formats
export const datas = [
{
id: 1,
name: "CODE_SLOT",
codePosition: 0,
codeType: "_",
slotPosition: 1,
slotType: "_",
},
{
id: 2,
name: "CODE-SLOT",
codePosition: 0,
codeType: "-",
slotPosition: 1,
slotType: "-",
},
];
Code for product code
export const getProductCode = (code, codePosition, codeType) => {
return (
code.replace(/\.[^/.] $/, "").split(codeType)[codePosition] ||
code.replace(/\.[^/.] $/, "").split(codeType)[0] ||
""
);
};
const images = [{
name: "toys-blue_wide.jpg"
}]
const selectedFileNameFormat = datas[0]
const output = images.map((image) => ({
productCode: getProductCode(
image?.name,
selectedFileNameFormat?.codePosition,
selectedFileNameFormat?.codeType
),
}));
console.log(output)
Expected Output for Product Code
productCode: toys-blue
Code for slot
export const getSlot = (slot, slotPosition, slotPosition) => {
return (
slot.replace(/\.[^/.] $/, "").split(slotPosition)[slotPosition] ||
slot.replace(/\.[^/.] $/, "").split(slotPosition)[0] ||
""
);
};
const images = [{
name: "toys-blue_wide.jpg"
}]
const selectedFileNameFormat = datas[0]
const output = images.map((image) => ({
slotCode: getSlot(
image?.name,
selectedFileNameFormat?.codePosition,
selectedFileNameFormat?.codeType
),
}));
Expected Output for slot
slotCode: wide
CodePudding user response:
If I'm understanding your question correctly, you want to parse/extract from a string, i.e. "toy-blue_wide.jpg", a productCode
everything before the "_"
character, i.e. "toy-blue"
, and a slotCode
, everything after the "_"
excluding the file extension. You can use a single REGEX and capture these two parts into their respective groups.
/^(.*)_(.*)\./
The first parens captures the product code and the second captures the slot code. Using