如何利用JavaScript正则表达式验证网址

JavaScript022

如何利用JavaScript正则表达式验证网址,第1张

用JavaScript的正则表达式验证网址格式是否正确,方法很多,这只是一个实现的方法.

代码如下:

<script type="text/javascript">

function IsUrl(str){

var regUrl = /(http\:\/\/)?([\w.]+)(\/[\w- \.\/\?%&=]*)?/gi

var result = str.match(regUrl)

if(result!=null) {alert( "Yes ")}

else {alert( "No! ")}

}

</script>

<script type="text/javascript ">

function IsUrl(str){

var regUrl = /(http\:\/\/)?([\w.]+)(\/[\w- \.\/\?%&=]*)?/gi

var result = str.match(regUrl)

if(result!=null) {alert( "Yes ")}

else{alert( "No! ")}

}

</script>

调用方法:

<Form name= "bao ">

<input TYPE= "text " NAME= "txt ">

<Input TYPE=BUTTON value= "TestURL " onClick= "IsUrl(document.bao.txt.value) ">

</FORM>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=UTF-8">

</head>

<body>

<input onblur="text()" id="text" type="text">

<script type="text/javascript">

function text(){

var string1 = document.getElementById('text')

var string2 = string1.value.indexOf('http://')

if(string2 != 0)

{

alert('你输入的网址不正确')

return false

}

else alert('合法')

}

</script>

</body>

</html>

<!-- 试试,是这样的效果吗? -->