views:

66

answers:

5

Hello,

Consider variable like

var url='http://www.example.com/index.php?id=ss';

or

var url='http://www.example.com/dir1/dir2/index.php';

In these variables, i want to get only the domain part i.e http://www.example.com, stripping out other texts. Is this possible in ordinary javascript or jquery ?

Please help

A: 

You can use a RegExp object.

kiamlaluno
A: 
var url='http://www.example.com/index.php?id=ss';
url = url.replace(/^.*?:\/\/(.*?)\/.*$/, "$1");

alert(url);
jAndy
A: 

An alternative using substrings and indexOf's :)

/* FUNCTION: getBaseUrl
 * DESCRIPTION: Strips a url's sub folders and returns it
 * EXAMPLE: getBaseUrl( http://stackoverflow.com/questions
 *   /3102830/stripping-texts-in-a-variable-javascript );
 * returns -- http://stackoverflow.com/
 */
function getBaseUrl( url ) {
    if ( url.indexOf('.') == -1 || url.indexOf('/') == -1 ) { return false; }

    var result = url.substr(0, url.indexOf( '/' , url.indexOf('.') ) + 1 );
    return( result );
}
abelito
This requires the domain name have a `.` in it. Would fail for eg. `http://localhost/`, `http://to/` or those integer-IP-address hacks, or IPv6 addresses.
bobince
+1  A: 

If you want to do this explicitly with URIs then you can use a js URI library for this. A sample library like js-uri

var url=new URI('http://www.example.com/dir1/dir2/index.php');
var sch = uri.scheme // http
var auth = uri.authority // www.example.com
naikus
+3  A: 

No need to wrangle URL strings. The browser has its own URL parser which you can get access to using the location-like properties of an HTMLAnchorElement:

var a= document.createElement('a');
a.href= 'http://www.example.com/index.php?id=ss';

alert(a.protocol); // http
alert(a.hostname); // www.example.com
alert(a.pathname); // /index.php
alert(a.search);   // ?id=ss
// also port, hash
bobince
+1 for a clever hack, although strictly speaking, it's not javascript.
just somebody
+1 from me too. Very clever
naikus