我试图从这样的字符串提升属性:
var valueAccessor = "function (){return { id:'someId',label:'Some Label',value:PropertyOnModel} }";
当我特别想从上述
value
中获取string
时,特别是使用以下代码,此方法有效:var value = valueAccessor.match(/function(?=[^}]*value\s?:\s?(\w+))/im)[1]
我有一个我想提升的不同属性的列表,例如label和id,所以我遍历它们并使用
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];
}
尽管propRegex源与第一个示例中的结构相同,但它返回
undefined
,因此意味着我无法提取相对值。谁能解释两者与我要去哪里的区别?
最佳答案
它是
new RegExp(pattern, flags);
所以您需要放下
/
并将im
移出var propRegex = new RegExp('function(?=[^}]*' + prop + '\\s?:\\s?(\\w+))', 'im');
参考:MDN RegExp constructor