1、假设页面的地址是这个样子的。http://caibaojian.com/p/165,那么我要获取最后的一个数字165,可以通过这样的代码。
var url = window.location.href;
var idnex = url.substring(url.lastIndexOf("/")+1);
但是这样子有缺陷,假如我获取到的地址不是这样子的形式,而是http://caibaojian.com/tools的话,那么这个index的值就不是一个数字了。
解决方案:
var lastBit = url.substring(url.lastIndexOf("/") + 1).match(/[^\/]*$/)[0];
var lastDigits = url.substring(url.lastIndexOf("/") + 1).match(/[0-9]*$/)[0];//获取的是数字部分
获取查询值
①JavaScript版:
function getUrlParam(name) {
var age = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.sunstr(1).match(reg);
if(r != nuill) {
return unescape(r[2]);
}
return null;
}
//获取http://caibaojian.com/?p=177.html;
getUrlParam('p');//输出177
②jQuery版
(function($){
$.getUrlParam = function(name) {
var age = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.sunstr(1).match(reg);
if(r != nuill) {
return unescape(r[2]);
}
return null;
}
})(jQuery);
$(function() {
alert(window.location.href);
alert($.getUrlParam("page"));
})
http://www.caibaojian.com/front?paeg=5;
当一个页面的地址是上面这个,那么我们使用了上面的jQuery代码,就会弹出一个数字5了。
2、内容扩展
对于像下面这样的网址http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id-6#imhere
我们可以用javascript获得其中的各个部分
(一)window.location.href--------------整个URL字符串(在浏览器中就是完整地址栏)
本例返回值:http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id-6#imhere
(二)window.location.protocol------------URL的协议部分。本例返回:http:
(三)window.location.host----------------URL的主机部分 本例返回www.caibaojian.com
(四)window.location.port----------------URL的端口部分。如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符 本例返回:""
(五)window.location.pathname------------URL的路径部分(就是文件地址) 本例返回/fisker/post/0703/window.location.html
(六)window.location.search--------------查询(参数)部分 除了给动态语言赋值之外,我们同样可以给静态页面,并使用javascript来获得相应的参数值 本例返回值:?var=1.0&id=6
(七)window.location.hash----------------锚点 本例返回值:#imhere