2011-12-09 82 views
1
var url_pattern = new RegExp("(?:http| https)://(www.|.*)someurlhere[.]com/\d\d\d\d/\d\d/\d\d/.*/", "i"); 
var url=window.location; //or could be document.URL both don't work 
url.match(url_pattern); 

爲什麼它返回null,或不確定的,但是當我扔的正則表達式爲檢查工作完美的,我只是想確保URL匹配JavaScript的正則表達式匹配返回null或undefined

+1

值得注意的是,window.location實際上是一個對象。位置上定義了許多可用和有用的屬性。請參閱:https://developer.mozilla.org/en/DOM/window.location –

+0

我添加到對象的toString(),它仍然給我一個NULL返回 – italiano40

+0

@PeterWagenet - 使用window.location需要一個字符串的上下文會自動調用toString(),它會給你完整的URL。如果這是你想要的,可能更好地使用'.href' proeprty,但是在大多數情況下都可以。 – jfriend00

回答

5

你有問題與您的斜線和https之前的一些額外的空間和一些週期字符不能正確逃脫。

使用new RegExp("string")格式時,必須將任何反斜槓加倍轉義。使用/regexhere/語法要容易得多,因爲您不必在許多正則表達式規則中使用雙轉義反斜槓。

此外,字符串有一個正則表達式方法,稱爲.match()。正則表達式本身有一個叫做的方法。 test().exec()。我建議這樣的:

var url_pattern = /(?:http|https):\/\/(www\.|.*)someurlhere\.com\/\d\d\d\d\/\d\d\/\d\d\/.*\//i; 
window.location.href.match(url_pattern); 

如果你想留在宣佈它的另一種方式,你會逃避每個反斜線:

var url_pattern = new RegExp("(?:http|https)://(www\\.|.*)someurlhere[.]com/\\d\\d\\d\\d/\\d\\d/\\d\\d/.*/", "i"); 
window.location.href.match(url_pattern); 
+1

您未能正確逃脫你的斜槓。這會產生一個語法錯誤。 –

+0

@PeterWagenet - 在哪裏?在第一種模式中,只有正斜槓需要轉義。在第二種模式中,只需要反斜槓。 – jfriend00

+0

@ jfriend00是在第一個投擲非法字符,但第二個作品像一個魅力感謝 – italiano40

0

雖然你應該考慮使用/regexhere/語法的建議jfriend00,您還可以使RegExp與RegExp.new語法一起工作。問題在於你在一個字符串中,所以你有任何反斜槓都被認爲是字符串本身的轉義字符,而不是RegExp。要解決此問題,您應該使用雙反斜槓。您的RegExp應更改爲:

new RegExp("/(?:http|https)://(www.|.*)someurlhere[.]com/\\d\\d\d\\d/\\d\\d/\\d\\d/.*/", "i");` 

您可能還需要對RegExp進行一些其他更改。例如,我建議使用\\.(再次注意在字符串中使用雙重轉義)來匹配週期而不是使用[.]