JavaScript RegEx: How do I utilise named capture groups?

64 views Asked by At

I am currently working at a Plugin for RPG Maker MZ and for that, i learned how to use RegEx for analyzing the Content of a Notetag. While my first try with them was actually pretty good, i assume it didn't used the full potential of RegEx and because i need to expand the my RegEx anyway so the user has more options, i wanted to try out named capture groups for better readability and easier access for me as a developer. Unfortionatly, i wasnt able to find out how to get the "group" object of the objects i got from the Iterator from matchAll(). So my question would be how to analyse the content of a named capture group in javascript.

Important: as far as i saw, the other questions didnt answer the question why i wasnt be able to find the right group object. also, most of the answers are with the exec function instead of the matchAll function.

The for this part relevant Code is:

const regex1new = /(?<ItemCategory>Item|Armor|Weapon)\s*:\s*(?<ID>\d+)\s*(?<Weight>w:(?<WeightFactor>\d+))?/gm;

let foundTagEntrysList = Array.from(this.enemy().meta.HellsCommonDropList.matchAll(regex1new), entry => entry[0]); //If you wanna reproduce this, just replace this.enemy().meta.HellsCommonDropList with a string

newTagsAnalyser();

function newTagsAnalyser() {
        foundTagEntrysList.forEach(matchedElement => {
            
                let Item;
                let Weight;
                let ID = matchedElement.groups.ID;
                    switch (matchedElement.groups.ItemCategory) {
                        case "Item":
                            Item = $dataItems[ID];
                            break;

                        case "Weapon":
                            Item = $dataWeapon[ID];
                            break;

                        case "Armor":
                            Item = $dataArmor[ID];
                            break;
                        default:
                            break;
                    }
                    if (typeof matchedElement.groups.Weight !== 'undefined'){
                        Weight = matchedElement.groups.WeightFactor; 
                    }
                commonItemDataMap.set(Item, Weight);

            
        });
    }

What did i expected? That the matechedElement.group.xxx returnes the content of the group that is named xxx.

What was the result? rmmz_managers.js:2032 TypeError: Cannot read property 'ID' of undefined

0

There are 0 answers