var url=document.location; url = "www.abc.com/sports/def.aspx"; var r = /\/(\w+)\.aspx/; alert(url.match(r)[1]); alert(r.exec(url)[1]);
var url=document.location.pathname.replace(/.*\//,''); var r = /\/(\w+)\.aspx/; alert(url.match(r)[1]); alert(r.exec(url)[1]);我把他放在aspx页面中运行时提示'match(...).1'为空或不是对象
var url=document.location; url = "www.abc.com/sports/def.aspx";url直接赋值是可以得到def...但是去掉url = "www.abc.com/sports/def.aspx"之后,直接用url=document.location;就会提示错误了。但var url=document.location; 这个本身已经获得了URL地址了,为何直接用这个就出错呢?
alert( document.location.pathname.replace(/.*\//g,''));
alert(document.location.pathname.replace(/.*\//,''))
比如www.abc.com/sports/def.aspx
JS里如何获取def 这个内容?其实我就只要def这个内容。URL我是能获取到的,不知道怎么操作这个字符串
var url=document.location;
url = "www.abc.com/sports/def.aspx";
var r = /\/(\w+)\.aspx/;
alert(url.match(r)[1]);
alert(r.exec(url)[1]);
var r = /\/(\w+)\.aspx/;
alert(url.match(r)[1]);
alert(r.exec(url)[1]);我把他放在aspx页面中运行时提示'match(...).1'为空或不是对象
url = "www.abc.com/sports/def.aspx";url直接赋值是可以得到def...但是去掉url = "www.abc.com/sports/def.aspx"之后,直接用url=document.location;就会提示错误了。但var url=document.location; 这个本身已经获得了URL地址了,为何直接用这个就出错呢?
http://school.itzcn.com/special-spid-28.html
上面讲解的比较详细,希望对楼主有所帮助。
提示'match(...).1'为空或不是对象
var path="www.abc.com/sports/def.aspx";
path=path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));
alert(path);
</script>
<script>
var path="www.abc.com/sports/def.aspx";
path=path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));
alert(path);
</script>
这样和正则的效率哪个高一些!
var path= document.location.href;
path=path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));
alert(path);
</script>我测试后这么写就可以获取到最后一节的目录名了。location.href获取的才是string类型,后面再substring才不会出错。如果像我这个简单的地址的话用字符串操作比正则表达式效率高点。但是包含了额外URL地址还是要用正则表达式了。