1

考虑变量

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

或者

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

在这些变量中,我只想获取域部分,即http://www.example.com剥离其他文本。这在普通的 javascript 或 jquery 中是否可行?

请帮忙

4

5 回答 5

4

无需争论 URL 字符串。浏览器有自己的 URL 解析器,您可以使用location-like 的属性访问它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
于 2010-06-23T17:13:15.540 回答
1

如果您想使用 URI 显式执行此操作,则可以为此使用 js URI 库。像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
于 2010-06-23T16:02:30.907 回答
0

您可以使用RegExp对象。

于 2010-06-23T15:07:40.810 回答
0
var url='http://www.example.com/index.php?id=ss';
url = url.replace(/^.*?:\/\/(.*?)\/.*$/, "$1");

alert(url);
于 2010-06-23T15:14:46.773 回答
0

使用子字符串和 indexOf 的替代方法 :)

/* 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 );
}
于 2010-06-23T16:00:57.507 回答