简体   繁体   English

Javascript 只返回字符串 url 的子域部分

[英]Javascript return only the subdomain part of a string url

I have a string that is typically a url (minus the http/www part).我有一个字符串,通常是一个 url(减去 http/www 部分)。 Keep in mind this string is returned via an API and not parsed from the browser url.请记住,此字符串是通过 API 返回的,而不是从浏览器 url 解析的。

For eg "xyz.abc.com or "login.xyz.abc.com"

Now I need to parse the string and return only the subdomain so that I get the following:现在我需要解析字符串并仅返回子域,以便获得以下信息:

"xyz" and "login.xyz"

With Python, I can achieve this using the following code:使用 Python,我可以使用以下代码实现这一点:

".".join(String.split(".")[:-2])

I am unable to find the appropriate syntax or equivalent in javascript.我无法在 javascript 中找到适当的语法或等效语法。

If you're sure that the URL will always have a subdomain (it won't be just abc.com , for example), and that the top-level domain will always consist of one part (it won't be co.uk , for example), you could do this with the following JavaScript:如果您确定 URL 将始终有一个子域(例如,它不会只是abc.com ),并且顶级域将始终由一个部分组成(它不会是co.uk ,例如),您可以使用以下 JavaScript 执行此操作:

 const exampleURL = "login.xyz.abc.com"; const splitURL = exampleURL.split("."); const subdomains = splitURL.slice(0, splitURL.length - 2); // Remove the domain const subdomainsString = subdomains.join(".") console.log(subdomainsString)

However, keep in mind that the conditions I mentioned above are two pretty big ifs: if an URL is returned as example.co.uk , this method would think that example would be the subdomain.但是,请记住,我上面提到的条件是两个非常大的 if:如果 URL 返回为example.co.uk ,则此方法会认为该example将是子域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM