Question

Im very new to Javascript and have created the following code through lots of googling and finally have it doing what it needs to however, I am sure i will have done it the messy way.

I want it to get the current URL, remove the domain, then replace any _ with a space and finally place that value in a div.

$(document).ready(function() {
//pure javascript
//var URLname = window.location;
var URLname = "www.blahblah.com/John_Smith";
var CutURL = URLname.substring(URLname.lastIndexOf("/"));
var result = CutURL.substring(1);
var result = result.replace(/_/g, ' ');
document.getElementById("URLHolder").innerHTML = result;
});

Have i done this in the simplest form already? I just think passing the variable though could be done in one go but I'm unsure 100% how.

I will have a further play as I wait for advice.

Many thanks.

Was it helpful?

Solution

It might be easier to use window.location.pathname which will return just the bit after the domain.

// with url: "www.blahblah.com/John_Smith";
var cutURL = window.location.pathname; // John_Smith
var result = cutURL.replace(/_/g, ' ');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top