Javascript哈希映射键编译成正则表达式
monthRegex正则表达式总是返回true,即使dateInput在我看来类似于“December 1,2008”,它也应该根据传入它的键匹配正则表达式。但事实并非如此,它只是返回true,并将“JAN”检测为月份Javascript哈希映射键编译成正则表达式,javascript,regex,Javascript,Regex,monthRegex正则表达式总是返回true,即使dateInput在我看来类似于“December 1,2008”,它也应该根据传入它的键匹配正则表达式。但事实并非如此,它只是返回true,并将“JAN”检测为月份 function dateFormat(dateInput) { var formattedDate = ""; var the_date, month, year; var monthHash = new Array(); mont
function dateFormat(dateInput) {
var formattedDate = "";
var the_date, month, year;
var monthHash = new Array();
monthHash['JAN']="01";
monthHash['FEB']="02";
monthHash['MAR']="03";
monthHash['APR']="04";
monthHash['MAY']="05";
monthHash['JUN']="06";
monthHash['JUL']="07";
monthHash['AUG']="08";
monthHash['SEP']="09";
monthHash['OCT']="10";
monthHash['NOV']="11";
monthHash['DEC']="12";
// Find which month we are dealing with
var whichKey = null;
for(var key in monthHash) {
var monthRegex = new RegExp(key, "i")
monthRegex.compile();
console.log("monthRegex.compile: " + monthRegex.test(dateInput));
if(monthRegex.test(dateInput))
{
whichKey = key;
break;
}
}
}
谢谢你,Andrew J.Leer第一句话:不要将数组用作关联数组!改用对象。或者以相反的方式使用数组 第二句话:为什么要使用正则表达式进行如此简单的搜索?请改用indexOf:
function dateFormat(dateInput)
{
var formattedDate = "";
var the_date, month, year;
var months = new Array("",
"jan", "feb", "mar",
"apr", "may", "jun",
"jul", "aug", "sep",
"oct", "nov", "dec"
);
// Find which month we are dealing with
for (var i = 1; i < months.length; i++)
{
if (dateInput.toLowerCase().indexOf(months[i]) > -1)
{
var whichMonth = months[i];
break;
}
}
if (whichMonth != undefined)
alert("Found: " + whichMonth);
}
dateFormat("10 Jun 2008");
删除“monthreex.compile();”行,它就可以工作了
这是因为monthreex.compile();将“”作为正则表达式进行遵从,因此所有内容都与之匹配。无需使用正则表达式进行普通的旧字符串匹配。您尤其不需要在每次调用函数时编译并丢弃12个正则表达式 更理智的版本:
// Get integer number of named month. 1-indexed for January;
// return 0 if unreadable name.
//
function readMonth(s) {
var begin= s.toLowerCase().substring(0, 3);
var ix= MONTHS.indexOf(begin);
if (ix==-1) return 0;
return ix/4+1;
}
var MONTHS= 'jan feb mar apr may jun jul aug sep oct nov dec';
给你道具,我的朋友!就这样!这也是个好主意,可能比循环更快,不过如果日期格式不同,我的第一个解决方案会更灵活一些。是的,我通常会选择数组,而不是空格分隔的字符串,但数组很烦人。indexOf()不是标准ECMA-262的一部分,也不受IE支持。
// Get integer number of named month. 1-indexed for January;
// return 0 if unreadable name.
//
function readMonth(s) {
var begin= s.toLowerCase().substring(0, 3);
var ix= MONTHS.indexOf(begin);
if (ix==-1) return 0;
return ix/4+1;
}
var MONTHS= 'jan feb mar apr may jun jul aug sep oct nov dec';