0

User inputs a web address that I want to get only the tail from, as I do know what site he inputs.

So first I want to remove the "main" URL and get what ever is at the end, so my action is:

Original link: http://example.com/something

var n=e.split("http://example.com/");e=n[1];

And I will get "something"

The problem is that site can also be secured, thus having https not http. Therefore the split wont work.

How do I define a split function, that would work like this:

split("http://example.com/ || https://example.com/")

I do not want to split by looking at "//" or anything of that sort, I want an exact address.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Yan
  • 582
  • 2
  • 6
  • 22

3 Answers3

1

If you wish to know the host you can do so by using this code instead in JavaScript:

window.location.host

Source Get The Current Domain Name With Javascript (Not the path, etc.)

You can also use window.location.path to get the URL that was requested, combining those you get:

window.location.host + window.location.pathname

For me, this outputs stackoverflow.com/posts/25203020/edit while writing this reply.

Community
  • 1
  • 1
Joeppie
  • 438
  • 3
  • 16
  • It's not a current URL but the one the user inputs in a field. – Yan Aug 08 '14 at 12:02
  • You should be **very** careful accepting input from the user: Wikipedia has this example URI: foo://username:password@example.com:8042/over/there/index.dtb?type=animal&name=narwhal#nose While a valid 'url' that you can click on, it is very complex and not a case you can easily anticipate. – Joeppie Aug 08 '14 at 12:42
  • But I do know the start of a URL, it can either be that or that. – Yan Aug 08 '14 at 15:32
1

If you like it clear and want to avoid regular expressions, try this:

var n=e.split("http://example.com/",2).pop().split("https://example.com/",2).pop();
chm-software.com
  • 351
  • 2
  • 10
  • It does work, however, I can't get the whole string at the end with e=n[1]; as I could before. – Yan Aug 08 '14 at 15:38
  • 1
    You don't need `n[1]`, the result of the combination of `split()` and `pop()` is a string stored in `n`. If you want `e` to become this string, just add `e = n`. – chm-software.com Aug 11 '14 at 09:36
0
var s = "http://example.com/something";
function split (url) {
  var r = /([^:]+):\/\/([^\/]+)\/(.*)/gi;
  var a = r.exec(url)
  return [a[1], a[2], a[3]];
}