Created
April 17, 2018 20:27
-
-
Save ondrej-kvasnovsky/bb2494577f4df63052c3aaf562060802 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data1 = { | |
attributes: { | |
domain: 'from.attributes.com' | |
} | |
} | |
const data2 = { | |
attributes: { | |
unknownAttributes: { | |
domain: 'from.unknownAttributes.com' | |
} | |
} | |
} | |
const data3 = { | |
attributes: { | |
url: | |
'https://www.fromurl.com/Zinus-SmartBase-Foundation-Replacement-Noise-Free/dp/B01GHHIWFO/ref=sr_1_1/146-9491966-1844353?ie=UTF8&qid=1521436930&sr=8-1&keywords=841550091137' | |
} | |
} | |
function getDomain(attributes) { | |
if (!attributes) { | |
return null | |
} | |
if (attributes) { | |
if (attributes.domain) { | |
return attributes.domain | |
} | |
const unknownAttributes = attributes.unknownAttributes | |
if (unknownAttributes) { | |
if (unknownAttributes.domain) { | |
return unknownAttributes.domain | |
} | |
} | |
const url = attributes.url | |
if (url) { | |
// const match = url | |
// .replace(/^(https?:)/i, '') | |
// .replace(/(www[0-9]?\.)/i, '') | |
// .split('/') | |
// return match[2] | |
const match = url.match(/:\/\/(www[0-9]?\.)?(.[^\/:]+)/i) | |
if (match !== null && match.length > 2 && typeof match[2] === "string" && match[2].length > 0) { | |
return match[2] | |
} else { | |
return null | |
} | |
} | |
} | |
} | |
console.log(getDomain(null)) | |
console.log(getDomain(undefined)) | |
console.log(getDomain(data1.attributes)) | |
console.log(getDomain(data2.attributes)) | |
console.log(getDomain(data3.attributes)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Regex details: https://regex101.com/r/fyZuSt/1