Skip to content

Instantly share code, notes, and snippets.

@martinloesethjensen
Last active May 5, 2024 04:37
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

@Allanksr
Copy link

Allanksr commented May 5, 2024

Very good, it worked perfectly here

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