开发者

Javascript & HTML Getting the Current URL

开发者 https://www.devze.com 2023-01-06 23:13 出处:网络
Can anyone help me. I don\'t use Client-side Javascript often with HTML. I would like to grab the current url (but only a specific directory) and place the results between a link.

Can anyone help me. I don't use Client-side Javascript often with HTML.

I would like to grab the current url (but only a specific directory) and place the results between a link.

So if开发者_运维知识库 the url is /fare/pass/index.html

I want the HTML to be <a href="#" id="whatever">pass</a>


This is a quick and dirty way to do that:

//splits the document.location.href property into an array
var loc_array=document.location.href.split('/');

//have firebug? try a console.log(loc_array);

//this selects the next-to-last member of the array.
var directory=loc[loc.length-2]


url = window.location.href // Not particularly necessary, but may help your readability
url.match('/fare/(.*)/index.html')[1] // would return "pass"


There may be an easier answer, but the simplest thing I can think of is just to get the current URL with window.location and use some type of parsing to get which directory you are looking for.

Then, you can dynamically append the HTML to your page.


This may get you started:

var linkElement = document.getElementById("whatever");
linkElement.innerHTML = document.URL.replace(/^(?:https?:\/\/.*?)?\/.*?\/(.*?)\/.*?$/i,"$1");
0

精彩评论

暂无评论...
验证码 换一张
取 消