Skip to content

Instantly share code, notes, and snippets.

@martinloesethjensen
Last active February 12, 2022 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinloesethjensen/f272fa448fc5be67d12b59ad9480ef95 to your computer and use it in GitHub Desktop.
Save martinloesethjensen/f272fa448fc5be67d12b59ad9480ef95 to your computer and use it in GitHub Desktop.
Kotlin string extension to apply https prefix to string.
/**
* Adds https prefix if link does not have prefix. It will also change old prefix http to https.
* @return link/url with https prefix
*/
fun String.toHttpsPrefix(): String? = if (isNotEmpty() && !startsWith("https://") && !startsWith("http://")) {
"https://$this"
} else if (startsWith("http://")) {
replace("http://", "https://")
} else this
@martinloesethjensen
Copy link
Author

You can also specify this on the function calls:

this.isNotEmpty()

@martinloesethjensen
Copy link
Author

You can test it out in the Kotlin Playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment