Skip to content

Instantly share code, notes, and snippets.

@ondrej-kvasnovsky
Created April 17, 2018 17:20
Show Gist options
  • Save ondrej-kvasnovsky/867d43ce0ec0c2791ebd95862796bafa to your computer and use it in GitHub Desktop.
Save ondrej-kvasnovsky/867d43ce0ec0c2791ebd95862796bafa to your computer and use it in GitHub Desktop.
extract domain from json and url
const data1 = {
attributes: {
domain: 'from.attributes.com'
}
}
const data2 = {
attributes: {
unknownAttributes: {
domain: 'from.unknownAttributes.com'
},
url:
'https://www.amazon.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'
}
}
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) {
let parts
if (url.search(/^https?\:\/\//) != -1) {
parts = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i, '')
} else {
parts = url.match(/^([^\/?#]+)(?:[\/?#]|$)/i, '')
}
return parts[1]
}
}
}
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