javascript獲取當前url


在WEB開發中,許多開發者都比較喜歡使用javascript來獲取當前url網址,本文就此為大家總結一下比較常用獲取URL的javascript實現代碼,以下示例是前面為相應實現方法,后面是獲取URL的效果,下面以例子講解:

輸入的網址是(沒有框架):http://localhost:81/Test/1.htm?Did=123
<br>以下為輸出:
<br>
<SCRIPT>

//獲取Url傳過來的值
function Request(name)
{
     new RegExp("(^|&)"+name+"=([^&]*)").exec(window.location.search.substr(1));
     return RegExp.$2
}

 

注意:RegExp 是javascript中的一個內置對象。為正則表達式
RegExp.$1是RegExp的一個屬性,指的是與正則表達式匹配的第一個 子匹配(以括號為標志)字符串,以此類推,RegExp.$2,RegExp.$3,..RegExp.$99總共可以有99個匹配
給你看了例子就知道了
var r= /^(\d{4})-(\d{1,2})-(\d{1,2})$/; //正則表達式 匹配出生日期(簡單匹配)
r.exec('1985-10-15');
s1=RegExp.$1;
s2=RegExp.$2;
s3=RegExp.$3;
alert(s1+" "+s2+" "+s3)//結果為1985 10 15

thisURL = document.URL;     // http://localhost:81/Test/1.htm?Did=123
thisHREF = document.location.href; // http://localhost:81/Test/1.htm?Did=123
thisSLoc = self.location.href;   // http://localhost:81/Test/1.htm?Did=123
thisDLoc = document.location;   // http://localhost:81/Test/1.htm?Did=123

thisTLoc = top.location.href;   // http://localhost:81/Test/1.htm?Did=123
thisPLoc = parent.document.location;// http://localhost:81/Test/1.htm?Did=123
thisTHost = top.location.hostname; // localhost
thisHost = location.hostname;   // localhost

thisU1 = window.location.protocol; // http:
thisU2 = window.location.host;   // localhost:81
thisU3 = window.location.pathname; // /Test/1.htm

document.writeln( thisURL + "<br />");
document.writeln( thisHREF + "<br />");
document.writeln( thisSLoc + "<br />");
document.writeln( thisDLoc + "<br />");

document.writeln( thisTLoc + "<br />");
document.writeln( thisPLoc + "<br />");
document.writeln( thisTHost + "<br />");
document.writeln( thisHost + "<br />");

document.writeln( thisU1 + "<br />");
document.writeln( thisU2 + "<br />");
document.writeln( thisU3 + "<br />");

document.writeln( "Did="+Request("Did") );// Did=123
</SCRIPT>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM