2011-12-14 127 views
2

任何人都可以告訴正則表達式在JavaScript中的URL驗證?URL中沒有www的驗證

我需要驗證爲http/https://example.com/...

我使用

((^http/://[a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)? 

,我試圖要檢查的例子進行了嘗試:

http://google.com 
https://google.com 
www.google.com 
+2

什麼是幾個有效的URL的例子?你上面提供的網址是無效的,如果我檢查正則表達式模式,它看起來像在那裏有幾個問題。 – Patrick 2011-12-14 13:37:05

+0

這可能是有用的:http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url – 2011-12-14 13:37:48

回答

0

嘗試:

function isUrl(s) { 
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)\ 
        (:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ 
    return regexp.test(s); 
} 

if (isUrl("your_url_here")) { 
    console.log("URL is valid"); 
} else { 
    console.log("URL is invalid"); 
} 

通過:http://snippets.dzone.com/posts/show/452

0

一個更簡化的版本可能是:^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(/\S*)?$ 我不知道這是不是夠你雖然,因爲我不知道你想要的結果做什麼。

1

你可以嘗試這樣的事:

var url = "Some url..."; 
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ 

if (regexp.test(url)) { 
    alert("Match"); 
} else { 
    alert("No match"); 
} 
0

也許你可能只是:

s,(https?://)(?!www\.),\1www.,

和使用jQuery驗證變換的串?

這將避免寫另一個正則表達式匹配一個URL的工作...