簡體   English   中英

剝離變量中的文本:javascript

[英]Stripping texts in a variable : javascript

考慮像這樣的變量

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中可能嗎?

請幫忙

無需糾纏URL字符串。 瀏覽器有自己的URL解析器,您可以使用HTMLAnchorElement location的屬性進行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

如果要使用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

您可以使用RegExp對象。

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

alert(url);

使用子字符串和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 );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM