Javascriptでワイルドカードを実現

サンプルコード:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>

<body>

</body>
</html>
<script language="JavaScript">

var PATTERN_LINE_START = "^";
var PATTERN_LINE_END = "$";
var META_CHARACTERS = ['$', '^', '[', ']', '(', ')', '{', '}', '|', '+', '.', '\\'];

function wildcard(pattern,word){
	var result = PATTERN_LINE_START;
	for(var i=0;i<pattern.length;i++){
		var ch = pattern.charAt(i);
		if(metaSearch(ch)){
			result += "\\" + ch;
            continue;
		}else{
			switch (ch) {
                case '*':
                    result += ".*";
                    break;
                case '?':
                    result += ".{0,1}";
                    break;
                default:
                    result += ch;
            }
		}
	}
	result += PATTERN_LINE_END;
	if(word.match(result) == null){
		return false;	
	}
	return true;
}
function metaSearch(ch){
	for(var metaCh in META_CHARACTERS){
		if(ch == metaCh ){
			return true;
		}
	}
	return false;
}

var data = "*.jpg";
alert(wildcard(data,"asd.jpgu"));
</script>

Source

Posted by arkgame