3

I can't read Java, I need an answer in Kotlin and I have read a thread in here: Get domain name from given url

say for example I have a string like this: "http://www.myWebsite.com/profile"

then how to programmatically get the domain name only in string like this "myWebsite.com" ?

sarah
  • 3,819
  • 4
  • 38
  • 80

1 Answers1

11

This is code from pointed question just translated to Kotlin. You can try it in Kotlin Playground.

import java.net.URI

fun main() {
    val url = "http://www.myWebsite.com/profile"
    val result = getDomainName(url)

    print(result)
}

fun getDomainName(url: String): String? {
    val uri = URI(url)
    val domain: String = uri.host
    return domain.removePrefix("www.")
}
Tomas Ivan
  • 2,212
  • 2
  • 21
  • 34