Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

javascript - 如何从JavaScript中的字符串中提取基本URL?(How to extract base URL from a string in JavaScript?)

I'm trying to find a relatively easy and reliable method to extract the base URL from a string variable using JavaScript (or jQuery).

(我正在尝试找到一种相对简单可靠的方法,使用JavaScript(或jQuery)从字符串变量中提取基本URL。)

For example, given something like:

(例如,给出如下内容:)

http://www.sitename.com/article/2009/09/14/this-is-an-article/

I'd like to get:

(我想得到:)

http://www.sitename.com/

Is a regular expression the best bet?

(正则表达式是最好的选择吗?)

If so, what statement could I use to assign the base URL extracted from a given string to a new variable?

(如果是这样,我可以使用什么语句将从给定字符串中提取的基本URL分配给新变量?)

I've done some searching on this, but everything I find in the JavaScript world seems to revolve around gathering this information from the actual document URL using location.host or similar.

(我已经对此进行了一些搜索,但我在JavaScript世界中找到的所有内容似乎都围绕着使用location.host或类似方法从实际文档URL收集此信息。)

  ask by Bungle translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit: Some complain that it doesn't take into account protocol.

(编辑:有人抱怨它没有考虑协议。)

So I decided to upgrade the code, since it is marked as answer.

(所以我决定升级代码,因为它被标记为答案。)

For those who like one-line-code... well sorry this why we use code minimizers, code should be human readable and this way is better... in my opinion.

(对于那些喜欢单行代码的人...很抱歉这就是为什么我们使用代码最小化,代码应该是人类可读的,这种方式更好......在我看来。)

var pathArray = "https://somedomain.com".split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;

Or use Davids solution from below.

(或者从下面使用Davids解决方案 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...