[英]How to add a subdomain to a URL string in NodeJS
I want to add a subdomain to a URL string in NodeJS, specificaly www
.我想在 NodeJS 中的 URL 字符串中添加一个子域,特别是
www
。 but only if the URL doesn't already have a one.但前提是 URL 还没有一个。
Examples of inputs:输入示例:
# changes
https://facebook.com/
facebook.com
# doesn't change
https://developers.facebook.com/
Their outputs:他们的输出:
# changes
https://www.facebook.com/
www.facebook.com
# doesn't change
https://developers.facebook.com/
There may be more eloquent ways to do it, but the following should accomplish what you want.可能有更多的 eloquent 方法可以做到这一点,但以下应该完成你想要的。 Essentially, you can check to see if there's only one
.
本质上,您可以检查是否只有一个
.
in the URL.在 URL 中。 If there is only one, then you're in need of a subdomain.
如果只有一个,那么您需要一个子域。
function formatUrl(url) { if((url.match(/\./g) || []).length > 1) { return url; } return url.replace('//', '//www.'); } console.log(formatUrl('https://developers.facebook.com/')) console.log(formatUrl('https://facebook.com/')) console.log(formatUrl('https://www.facebook.com/'));
You can do it by finding number of dots in URL, if they are more than 1 then www
can be applied.您可以通过查找 URL 中的点数来做到这一点,如果它们大于 1,则可以应用
www
。
let url = "https://facebook.com/"; url = getURL(url); console.log(url); console.log(getURL("sbc.someurl.com/sometopic/hello.world")); function getURL(url){ url = url.split("//"); let isHttps = url.length > 1? url[0]: false; if(url && url.length > 1){ url = url[1]; // someurl.com/sometopic/hello.world } else{ url = url[0]; } let a = url.split("/"); let u = a[0]; // someurl.com let arr = u.split("."); if(arr.length > 2){ console.log("No need for www"); } else{ a[0] = "www." + a[0]; } if(isHttps){ return isHttps + "//" + a.join("/"); } else{ return a.join("/"); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.