Javascript Hashmap键编译成正则表达式

时间:2008-11-19 16:51:34

标签: javascript regex

monthRegex正则表达式总是返回true,即使dateInput类似于“2008年12月1日”,我认为它应该通过我传入其中的任何键来匹配正则表达式。但事实并非如此,它只返回true,并将“JAN”视为月份。

    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

3 个答案:

答案 0 :(得分:3)

第一句话:不要将Array用作关联数组!请改用Object。或者以相反的方式使用Array。

第二句话:你为什么要使用正则表达式进行这种简单的搜索?请改用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");

如果你真的想使用正则表达式,留在主题中,这是另一种方式:

function dateFormat(dateInput) 
{
  var formattedDate = "";

  var the_date, month, year;

  var months = /(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i;

  // Find which month we are dealing with
  var matches = dateInput.match(months);
  if (matches != null)
    alert("Found: "  + matches[1]);
}
dateFormat("December, 10 2008");

答案 1 :(得分:2)

删除“monthRegex.compile();”线,它的工作原理。

这是因为monthRegex.compile();将“”视为正则表达式,因此一切都符合它。

答案 2 :(得分:0)

您不需要将正则表达式用于普通旧字符串匹配。每次调用函数时,您都不需要编译并丢弃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';