2016-11-29 155 views
0

我有下面的正則表達式測試,它正在尋找格式爲nn/nnnn的日期,並且是01-12/20nn或01 -12/19nn - 即一個月之後的一年,這很有意義。Javascript正則表達式對象在Chrome,Firefox但不在IE 11(正則表達式中的語法錯誤)

我這是什麼/^([0-1][0-9][\/]([1][9]|[2][0])[0-9][0-9])$/這對IE 11

正則表達式也傳遞www.regex101.com測試適用於Chrome和Firefox罰款,但失敗,出現錯誤Syntax error in regular expression和預期有執行。

我已經在下面列出了一個完整的例子 - 我有點卡住了,因爲我確定這個正則表達式是絕對正確的。

任何幫助將不勝感激 - 我做錯了什麼?

<!DOCTYPE html> 
<html lang="en"> 
    <head> 

    <title>This is the title</title> 

    <script type="text/javascript"> 

     var pattern = new RegExp(/^([0-1][0-9][\/]([1][9]|[2][0])[0-9][0-9])$/, 'i'); 

     var goodInput = "12/2012"; 
     var badInput = "1b/g212"; 

     if(!pattern.test(goodInput)) 
     { 
      console.log("Good Input was NOT OK"); 
     } 
     else 
     { 
      console.log("Good Input was OK"); 
     } 

     if(!pattern.test(badInput)) 
     { 
      console.log("Bad Input was NOT OK"); 
     } 
     else 
     { 
      console.log("Bad Input was OK"); 
     } 

    </script> 

    </head> 

    <body> 

    This is the body 

    </body> 
</html> 
+0

如果沒有字符串,則不需要'new RegExp'。 'var pattern =/^([0-1] [0-9] [\ /]([1] [9] | [2] [0])[0-9] [0-9])$/i ;' – epascarello

回答

2

您正在從現有正則表達式創建new RegExp。這是IE11不支持的ES6功能。詳情請參閱this blog post。關於此用法的瀏覽器兼容性詳細信息可參見here。它在the spec;注意patternIsRegexp的情況。

以下任一操作將工作:

var pattern = /^([0-1][0-9][\/]([1][9]|[2][0])[0-9][0-9])$/i; 

var pattern = new RegExp("^([0-1][0-9][/]([1][9]|[2][0])[0-9][0-9])$", "i"); 

順便說一句,你爲什麼寫[1]而不是1?你爲什麼要寫[\/]而不是\/