如何从anchor href属性获取域名?
我有一个像以下url:
http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226
我只想在我的链接文字中:
http://www.intereconomia.com
但是href转到:
http://www.intereconomia.com/noticias-gaceta/politica/grinan-los-casos-corrupcion-pueden-influir-20120226
什么正则表达式jquery可以做这个function?
而不是使用正则表达式,你可以尝试这是干净和简单的。
$('a').each(function(){ $(this).text(this.protocol + "//" + (this.hostname || this.pathname)); });
注意:如果您只想为锚点设置它,那么相应地更改选择器,但内部逻辑保持不变。
听起来你要求一个简单的锚标记(如果你需要一些特定的jQuery / JavaScript动作,请详细说明):
http://www.intereconomia.com
您可以添加要显示的链接文本:
Click Here
但是,我不建议制作文本http://www.intereconomia.com
因为当用户期望访问http://www.intereconomia.com
时,这通常被视为链接到内页的不良做法http://www.intereconomia.com
而是使用描述性链接来掩盖url。
//wait for `document.ready` to fire so the DOM elements are available to modify $(function () { //iterate through all the `` elements in the DOM $.each($('a'), function () { //get the text of the current `` element and then use RegExp to get everything after the `.com/` var url = $(this).text(), other = url.replace(/^(http|https):\/\/(.){0,99}(\.com|\.net|\.org)/, ''); //now change the text of this `` element to not display anything after the `.com/` $(this).text(url.replace(other, '')); }); });
可能有更优雅的解决方案,但这应该可以解决问题。
这是一个演示: http : //jsfiddle.net/jasper/DssEs/2/