JavaScript RegEx: How do I utilise named capture groups? [duplicate] - javascript

This question already has answers here:
Javascript: Named Capture Groups
(2 answers)
Named capturing groups in JavaScript regex?
(10 answers)
Closed last month.
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

Related

RegExp doesn't produce expected result but it does everywhere else [duplicate]

This question already has answers here:
RegEx to extract all matches from string using RegExp.exec
(19 answers)
Closed 5 years ago.
I'm getting started with Node.js and trying to learn it, coming from PHP environment.
I have following RegExp: /([A-Z]{2,})+/gim (two or more letters next to each other).
I have following string: "That's my testing sample but it doesn't work."
So I throw this into Node.js (keep in mind I'm a newbie):
var fs = require("fs");
var request = require("request");
// COMMENTS
var regex = new RegExp(/([A-Z]{2,})+/gim);
//COMMENTS
var thisyear = regex.exec("That's my testing sample but it doesn't work.");
console.log(thisyear);
This is the file in it's entirety.
The output that it returns:
[ 'That',
'That',
index: 0,
input: 'That\'s my testing sample but it doesn\'t work.' ]
The output according to pretty much every site I tested it on:
That
my
testing
sample
but
it
doesn
work
How do I get each separate result in an array of sorts?
P.S.: match() and test() are "not a function".
To get multiple results with the g flag, you call .exec() multiple times like this:
let regex = /([A-Z]{2,})+/gim;
let str = "That's my testing sample but it doesn't work.";
let results;
while ((results = regex.exec(str)) !== null) {
console.log(results[0]);
}
Javascript will set the .index property on the regex object to keep track of where it is searching in the source string and each time you call it, it will return the next set of results.
Note: When using the literal form of a regex /something/, you do not put it inside a new RegExp() constructor. The language makes you a regex object automatically when using the literal syntax.
FYI, you can get all the matches without using a while look like this:
let re = /([A-Z]{2,})+/gim;
let str = "That's my testing sample but it doesn't work.";
console.log(str.match(re));
This is generally the simpler way to do it unless you need to get the groups from your regex. If you need to groups rather than just the whole match, then you have to use the .exec() form to get multiple matches, each with multiple groups.

Query syntax for JSON lookup data with var ( not condition ) [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I'm trying to filter some JSON data, but I would like the lookup to be based on selection of a drop down. However, I just can't get the syntax correct when trying to do this. Currently the following works in my code, great:
var as = $(json).filter(function (i, n) {
return (n.FIELD1 === "Yes"
});
However, what I would like to do is replace the FIELD1 value with a var from the drop down. Something like this following, which is not working:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
return (n.dropdownResult === "Yes"
});
I'm trying to get the var to become the field name after the n. but it's not working.
Thanks for your time. Sorry if this has been answered many times before and is obvious to you.
To use a variable value as the key of an object you should use bracket notation, like this:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
return n[dropdownResult] === "Yes";
});
I removed the extraneous ( you left in your code - I presume this was just a typo as it would have created a syntax error and stopped your code from working at all.
Also note that it's much better practice to use a boolean value over a string 'Yes'/'No'

jQuery Multiple Strings Case and Accent Insensitive

My first post on here. I have a function on a website whereby a randomly generated French phrase is displayed, challenging the reader to translate it into English in a text box. On clicking on a button, the text entered is compared to all the possible answers (there are multiple correct translations for a given phrase). I've looked around for answers on this but nothing seems to suit my situation.
Here's the jQuery:
var correctAnswer = function(){$('#correctmessage').show('fast');$('#errormessage').hide('fast');}
var wrongAnswer = function(){$('#errormessage').show('fast');$('#correctmessage').hide('fast');}
$('#1').find('button').on('click', function(){
var text = $(this).parent().find('.translatefield').val();
var compareText = "I went to the cinema";
var compareText2 = "I have been to the cinema";
if (text == compareText || text == compareText2) {
correctAnswer();
}
else {
wrongAnswer();
}
});
So I wondered if I can put the 'compare' variables into one variable i.e. 'I went to the cinema OR I have been to the cinema OR etc etc' within one variable for tidiness. But mainly I need to know how I can call that variable within the if so that it also accepts the answer without accented characters and regardless of upper or lower case... I hope this is clear! Thanks for any help you can give, this has been irritating me for a while!
As commented by Mark Holland, use arrays for the compare phrases.
If you are using jQuery anyway, you could use jQuery.inArray().
https://api.jquery.com/jQuery.inArray/
var compareText = ['i went to the cinema','i have been to the cinema'];
if ($.inArray(text.toLowerCase(), compareText)) {
... do stuff
}
To ignore the accents, use a solution like this:
String.prototype.removeAccents = function(){
return this
.replace(/[áàãâä]/gi,"a")
.replace(/[éè¨ê]/gi,"e")
.replace(/[íìïî]/gi,"i")
.replace(/[óòöôõ]/gi,"o")
.replace(/[úùüû]/gi, "u")
.replace(/[ç]/gi, "c")
.replace(/[ñ]/gi, "n")
.replace(/[^a-zA-Z0-9]/g," ");
}
Credits to Luan Castro
Perform a find/match with javascript, ignoring special language characters (accents, for example)?
As mentionned by Mark Holland, arrays would answer your first question.
JS arrays
To ignore accents, a quick search gave me this answer:
Replace accents
And to ignore lower/uppercase, a quick search gave me this answer.
Ignore case
How about setting the strings into one array and iterate this array to compare with the answer?

javascript regex match not working as expected

I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});

Getting the first item in an [word, word] [duplicate]

This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow

Categories