简体   繁体   中英

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 . but only if the URL doesn't already have a one.

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. Essentially, you can check to see if there's only one . in the 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.

 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("/"); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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