简体   繁体   English

使用Javascript从链接文本中删除前缀

[英]Removing prefixes from link text using Javascript

I've got a directory listing script that outputs the names of various organisations and their website address. 我有一个目录列表脚本,该脚本输出各种组织的名称及其网站地址。 The link that to the website that the user sees looks like http://www.whatever.com or http://whatever.com 用户看到的网站链接看起来像http://www.whatever.comhttp://whatever.com

To make things look a little prettier I'd like to remove the http:// element of the link. 为了使外观看起来更漂亮,我想删除链接的http://元素。 So the end result from the user perspective should, in html terms, look like justthedomainname.com 因此,从用户角度来看,最终结果应该以html的形式看起来像justthedomainname.com

The way in which the php script is written and outputs makes doing this a little bit of a pain, and I thought it might be easier to accomplish with some javascript instead. 编写和输出php脚本的方式使执行此操作有些麻烦,我认为使用某些javascript可能更容易完成。

I initially tried something like: 我最初尝试过类似的方法:

<script>
var curInnerHTML = document.body.innerHTML;
curInnerHTML = curInnerHTML.replace("http://", "");
document.body.innerHTML = curInnerHTML;
</script>

This however doesn't work, because it's looking for an exact string of "http://", when this will always be followed by the actual domain. 但是,这是行不通的,因为它一直在寻找一个确切的字符串“ http://”,而该字符串将始终跟在实际的域之后。

Any idea how I can accomplish this in pure JS? 知道如何在纯JS中完成此操作吗?

You need a regex instead of a string. 您需要一个正则表达式而不是字符串。 Something like this. 这样的事情。

curInnerHTML = curInnerHTML.replace(/^https?:\/\//i, "");

If I understood you correctly, you want to remove http://www. 如果我对您的理解正确, http://www.删除http://www. from a string containing URL of some website. 从包含某些网站URL的字符串中获取。

You can do it with regex 你可以用正则表达式来做

let result = url.replace(/^(https?:\/\/)?(www\.)?/,'', '');

If you only want to strip http:// and keep www then use this regex 如果您只想剥离http://并保留www ,请使用此正则表达式

let result = url.replace(/(^\w+:|^)\/\//,'', '');

Here is a working snippet 这是一个工作片段

 let url = "http://www.whatever.com"; let result = url.replace(/^(https?:\\/\\/)?(www\\.)?/,'', ''); console.log(result); 

If you're looking for <a> elements exclusively and are only trying to replace the text content that the [user] sees: 如果您仅在寻找<a>元素并且仅尝试替换[用户]看到的文本内容:

document.querySelectorAll( 'a[href^="http"]' ).forEach( function ( current ) {
    current.textContent = current.href.split('//')[ 1 ];
} );

With a caveat about .forEach() on a .querySelectorAll() NodeList 关于.querySelectorAll() NodeList上有关.forEach()警告

Try this 尝试这个

 function remove(){ var a = document.getElementById('target').getElementsByTagName('a'); var attr; for (var i = 0; i < a.length; i++) { attr = a[i].getAttribute("href").replace("http://", ""); a[i].text = attr; } } remove(); 
  <div id="target"> <a href="http://test1.com">http://test1.com</a> <a href="http://test2.com">http://test2.com</a> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM