我正在寻找一种更优雅的方式在控制结构中使用正则表达式。我希望能够使用匹配执行操作,而无需在正确的位置之外声明正则表达式,或者必须执行两次匹配操作。
以下是为简洁起见编写的代码:
/* I'm not a fan of declaring this outside of where it will be used */
var regexYoutube = new RegExp(/((youtube\.com\/watch\?v=)|(youtu\.be\/))(.{11})/i);
if(isImage(content)){
data.type = 'IMAGE';
data.content = toImage(content);
postContent(data);
} else if (isVideo(content)){
data.type = 'VIDEO';
data.content = getVideoThumb(content);
postContent(data);
} else {
data.type = 'STRING';
data.content = content;
postContent(data);
}
function isImage(content){
if(content.indexOf(".jpg") > -1)
return true;
else
return false;
}
function isVideo(content){
return regexYoutube.test(content);
}
function getVideoThumb(content){
/* I don't want to perform a test followed by an exec */
var youtubeMatch = regexYoutube.exec(content);
return "http://img.youtube.com/vi/"+youtubeMatch[4]+"/0.jpg";
}
我离开这是非常挑剔的,但如果它是一个必要的邪恶,我会接受它。
答案 0 :(得分:0)
我将isVideo
函数修改为其他内容,例如execYouTubeRegex
,并返回.exec的值。然后,不是在execYouTubeRegex
之外声明正则表达式,而是在函数内声明它。
然后,您可以通过调用isYoutube
替换execYouTubeRegex
并检查它是否返回任何内容,并使用相同的函数替换您在其他地方使用的exec调用。
这是一种以自己的方式存在的邪恶,因为它将函数的副作用用于其他东西(简单的返回值是检查)。但它可以替代在未使用的地方定义正则表达式。
评论中提到的并不是真的那么邪恶。保持你的范围小,它不会太混乱 - 代码对我来说是非常可读的。