我正在尝试从Javascript中的字符串中提取与给定模式匹配的子字符串。示例:
var classProp = 'active category_games',
match = classProp.match(/category_[a-z]+\b/),
category;
if(match !== null && match.length > 0){
category = match[0];
}有没有更简单的方法来解决这个问题呢?一行代码,最好是?
发布于 2011-12-06 19:39:36
在分类之前应该有一个\b吗?
如果匹配失败,你可以通过提供一个空数组来缩短它;
category = (classProp.match(/category_[a-z]+\b/) || [""])[0];发布于 2011-12-06 19:35:59
好了,这已经非常接近一行了。您可以将"if“代码块简化为以下代码:
if(match){
category = match[0];
}发布于 2011-12-06 19:40:19
这样如何:
try { var category = 'active category_games'.match(/category_[a-z]+\b/).pop(); } catch(e) {}https://stackoverflow.com/questions/8399178
复制相似问题