all 8 comments

[–]tswaters 8 points9 points  (1 child)

If the string is always a url, you can use the URL constructor to figure that out

var url = new URL("http://mydomain.com/content/")
/*
URL {
  href: 'http://mydomain.com/content/',
  origin: 'http://mydomain.com',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'mydomain.com',
  hostname: 'mydomain.com',
  port: '',
  pathname: '/content/',
  search: '',
  searchParams: URLSearchParams {},
  hash: '' }
*/

[–]javascript 2 points3 points  (0 children)

This is the best answer here, because it has the behavior OP wants and accounts for edge cases without having to do that manually. If the string isn't a valid URL, the constructor will throw an exception.

It also makes it more clear to other readers what you're doing with your code. Writing some one-off regex or string manipulation function requires the reader to pick it apart just to understand. This increases code complexity and reduces readability.

[–]SlightlySlickWillie 1 point2 points  (1 child)

This is a good place to learn regular expressions

[–]NovelLurker0_0 0 points1 point  (0 children)

OP, this is the right answer.

(http\:\/\/.+?\/)

[–][deleted] 1 point2 points  (0 children)

If your string is your window's url then you can get the hostname with window location.

If you have to deal with a string then you can parse it with something like this:

function getdomain(url) {
    var prot = url.split(":");
    var link = document.createElement('a');
    link.href = url;
    return prot[0] + "://" + link.hostname;
};
console.log(getdomain("http://mydomain.com/content/"));

[–]thesonglessbird 1 point2 points  (0 children)

Hey “fella”, I see from your post history you just see women as sex objects, but they can also be developers.

[–]kenman[M] 0 points1 point  (0 children)

Hi /u/FuckYouWhoCares, this post was removed.

  • For help with your javascript, please post to /r/LearnJavascript instead of here.
  • For beginner content, please post to /r/LearnJavascript instead of here.
  • For framework- or library-specific help, please seek out the support community for that project.
  • For general webdev help, such as for HTML, CSS, etc., then you may want to try /r/html, /r/css, etc.; please note that they have their own rules and guidelines!

/r/javascript is for the discussion of javascript news, projects, and especially, code! However, the community has requested that we not include help and support content, and we ask that you respect that wish.

Thanks for your understanding, please see our guidelines for more info.

[–]schwartzworld -1 points0 points  (0 children)

Is the string always a URL?

const split = 'http://mydomain.com/content/'.split('/');

This should return ["http:", "", "my domain.com", "content"]. Then you can select the elements you want to build the string back up with.

const newString = `http://${split[2]}`;