SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Member
    Join Date
    Jan 2005
    Location
    ss
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Get domain name script

    Hi All

    I'm looking for some help with getting a domain name from a url e.g.

    http://www.enerweb.co.za if would like the 'enerweb' part or
    http://slashdot.org the 'slashdot' part.

    Thanks

    Vickus

  2. #2
    SitePoint Evangelist SpaceFrog's Avatar
    Join Date
    Jan 2005
    Location
    Outerspace
    Posts
    511
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    here is one way of doin it
    Code:
    <script>
    var myurl="http://here.co.uk" //what ever url you want
    var taburl=myurl.split('\.')
    var start = taburl[0].length
    var domain=(taburl[0].substring(start-3)=="www")?taburl[1]:taburl[0].split('\/\/')[1];
    alert (domain)
    </script>

  3. #3
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why are you escaping characters in a string?

    split('\.')
    split('\/\/')


    Here is another way:
    Code:
    var str =   "http://www.enerweb.co.za";
    // str =   "http://slashdot.org";
    
    var start, end;
    
    if(str.indexOf("www") == -1)
    {
    	start = str.indexOf("//") + 2;
    	end = str.indexOf(".");
    }
    else
    {
    	start = str.indexOf(".") + 1;
    	var chopped = str.substring(start); //the substring from start to the end of the string
    	end = chopped.indexOf(".") + start;
    }
    
    var domain = str.substring(start, end);
    alert(domain);
    or
    Code:
    var str = "http://www.enerweb.co.za";
    str = "http://slashdot.org";
    
    var pieces = str.split(".");
    var domain;
    
    if (pieces[0].indexOf("www") == -1)
    {
    	var start = pieces[0].indexOf("//") + 2;
    	domain = pieces[0].substring(start);
    }
    else
    	domain = pieces[1];
    
    
    alert(domain);
    Last edited by 7stud; Feb 16, 2005 at 11:57.

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ...and if you are comfortable using regex's:

    Code:
    var regex = /\/\/(www.)?([^.]+)/i;
    var matches_array = str.match(regex);
    alert(matches_array[2]);
    The matches array will contain the actual match at index 0, with the first parenthesized submatch at index 1, and the second parenthesized submatch at index 2, etc.

  5. #5
    SitePoint Evangelist SpaceFrog's Avatar
    Join Date
    Jan 2005
    Location
    Outerspace
    Posts
    511
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yeah just a bad habit of escaping everything like for regExp ...
    But as long as it does the job ;-))


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •