我试图从这样的字符串提升属性:

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

10-05 20:53
查看更多