1

I am trying to get hostname from set of urls that my webapp can encounter with. The desired output should be something like http://localhost/Webapp/, ending at /Webapp/ and everything after that should be removed.

Kindly note that I dont want to use word Webapp in regex as this name is dynamic and used for demo/testcase only.this can be anything , not harcoded.

In real example I am using location.href.replace(/index.+/g, "").replace(/#.+/g, "") and I want to keep only hostname ending atWebapp/.

Problem: my solution seems to working fine except "http://localhost/Webapp/#" is not working correctly ? why is that ? see fiddle below

JSFIDDLE: http://jsfiddle.net/bababalcksheep/um0uqb8v/ JS:

var getHost = function (url) {
    return url.replace(/index.+/g, "").replace(/#.+/g, "")
};
var urls = [
     "http://localhost/Webapp/",
    "http://localhost/Webapp/#",
    "http://localhost:8080/Webapp/#sdf#dfgdf#fdg",
    "12.168.1.1:8080/Webapp/index.html#",
    "https://localhost/Webapp/index.html#ab#bg",
    "https://localhost/Webapp/index.html"
];
//Print all urls
$.each(urls, function () {
    $("<p/>").text(getHost(this)).appendTo($(".test"));
});

3 Answers 3

4

Use url.match(/https?:\/\/([^\/]+)/);

EDIT:

It returns an array where the 1st element is the host with protocol and the 2nd without.

Sign up to request clarification or add additional context in comments.

Comments

3

You can try removing anything after the last slash (files and hash-es):

var getHost = function (url) {
    return url.replace(/\/[^/]*?$/, '/');
};

And here's the updated fiddle.

Comments

3

There's a bit of a trick you can use to get the browser to extract the hostname for you.

var getHost = function (url) {
    var a = document.createElement('a');
    a.href = url;
    return a.hostname;
};

It also appears you want the path as well. You can access it with the pathname property of the a element. If you're doing that, you ought to rename the function to something like getHostAndPath().

1 Comment

@django no, it doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.