请注意,我知道我想要隔离的完整类是什么,只有它的格式,例如:
class="loadable context-enc encounterTimelineEncounterDateitem"
我正在寻找的是context-enc或匹配的内容:
.match(/\bcontext-[a-z]+\b/)
它确实是我想要发现的[a-z] +部分。我不想那么多测试是否有匹配的类,但想知道“context-”之后的字符串是什么(在这种情况下是'enc')。类似的东西:
function getcontext(class, 'context-'){ .. }
答案 0 :(得分:2)
您可以将正则表达式中的[a-z+]
包装在括号中,以便将值重新包含在捕获组中:
"context-enc".match(/\bcontext-([a-z]+)\b/)
[" context-enc"," enc"]
答案 1 :(得分:0)
以下功能可能会返回您想要的内容......
function getContext(className, withString){
var r = new RegExp("\\b"+ withString +"[a-z]+\\b");
var s = new RegExp("^"+withString);
return className.match(r)[0].replace(s,'');
}
如果您动态构建正则表达式,则可以将变量内容插入其中,然后隔离[a-z]+
部分,只需从结果中删除搜索到的字符串。
编辑:使用@ nathan-taylor的捕获组建议我们可以将功能简化为:
function getContext(className, withString){
var r = new RegExp("\\b"+ withString +"([a-z]+)\\b");
return className.match(r)[1];
}