deanboysupreme
deanboysupreme

Reputation: 87

remove text from url string javascript

I want to display, with javascript, just the filename of the page the user is on. For example,

https://test.example.com/wow.html

should return

wow

I was trying to use the replace() method, like so:

var url = document.URL;
document.getElementById("code").innerHTML = url.replace("http://test.example.com/", " ");

But I can't figure out how to remove the .html extension as well, or also replace https urls. Is there a better way to do this?

Thanks.

Upvotes: 2

Views: 4957

Answers (5)

Liam Marshall
Liam Marshall

Reputation: 1613

There's a little hack using an <a> element that works as such:

var parser = document.createElement('a');
parser.href = "http://example.com/foo.html";
parser.pathname; // => "/foo.html"

You can parse off the / and the .html however you want, but you'll always get the correct path back from .pathname.

See here for more info about this method.

Upvotes: 2

ncubica
ncubica

Reputation: 8495

Another possible way to do it.

var url = "https://test.example.com/wow.html"

var urlSplit = url.split("/");
var name = urlSplit[urlSplit.length-1].split(".")[0];
console.log(name);

// this will fail of course with a name like my.page.html but this is just to give another alternative. :)

Upvotes: 2

user1009835
user1009835

Reputation:

var text = "https://test.example.com/wow.html";
var new_text = text.slice(text.indexOf("//") + 2, text.indexOf(".html")).split('/');
console.log(new_text[1]);

Upvotes: 0

Matt Zeunert
Matt Zeunert

Reputation: 16571

You probably want to use regular expressions, like this:

"https://test.example.com/wow.html".match(/https?:\/\/test\.example\.com\/(\w*).html/)
// Returned list: ["https://test.example.com/wow.html", "wow"]

When starting out a tool like Regex101 can be useful to make sense of the expression:

enter image description here

Upvotes: 0

lssilveira
lssilveira

Reputation: 62

This might work for you:

document.getElementById("code").innerHTML = url.substring(url.lastIndexOf("/"), url.lastIndexOf("."));

Upvotes: 0

Related Questions