Reputation: 41
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
To make things look a little prettier I'd like to remove the http:// element of the link. So the end result from the user perspective should, in html terms, look like 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.
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.
Any idea how I can accomplish this in pure JS?
Upvotes: 0
Views: 1049
Reputation: 1353
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>
Upvotes: 0
Reputation: 1607
If you're looking for <a>
elements exclusively and are only trying to replace the text content that the [user] sees:
document.querySelectorAll( 'a[href^="http"]' ).forEach( function ( current ) {
current.textContent = current.href.split('//')[ 1 ];
} );
With a caveat about .forEach()
on a .querySelectorAll()
NodeList
Upvotes: 0
Reputation: 5079
If I understood you correctly, you want to remove http://www.
from a string containing URL of some website.
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
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);
Upvotes: 0
Reputation: 1529
You need a regex instead of a string. Something like this.
curInnerHTML = curInnerHTML.replace(/^https?:\/\//i, "");
Upvotes: 1