I am trying to lift properties from a string like this:
var valueAccessor = "function (){return { id:'someId',label:'Some Label',value:PropertyOnModel} }";
This works when I specifically want to get value from the above string, specifically using this code:
var value = valueAccessor.match(/function(?=[^}]*value\s?:\s?(\w+))/im)[1]
I have a list of the different properties I want to lift, for example label and id so I iterate through them and dynamically set my regex using RegExp.
// Iterate through id, label, value
for(var prop in obj) {
var propRegex = new RegExp('/function(?=[^}]*' + prop + '\\s?:\\s?(\\w+))/im');
var propValue = valueAccessor.match(propRegex)[1];
}
Although the propRegex source is identical to the structure in the first example, it returns undefined and thus means I can't extract the relative values.
Can anybody explain the difference between the two and where I am going wrong?
new RegExp(pattern, flags);/are the delimiters of the regex literal, just like"are the delimiters of a string. They tell the parser where the pattern starts and ends. They are not part of the value (pattern) itself. If you don't use a regex literal, don't put/around the pattern.