Last active
October 14, 2022 10:43
-
-
Save mr5z/de15062108a8c4e0375a88f401e098f0 to your computer and use it in GitHub Desktop.
Trying to replicate C#'s Uri.EscapeUriString()
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
fun tryEncode(url: String): URL { | |
val schemeSeparator = "://" | |
val schemeIndex = url.indexOf(schemeSeparator) | |
val scheme: String | |
val urlWithoutScheme: String | |
if (schemeIndex > 0) { | |
scheme = url.substring(0, schemeIndex) | |
urlWithoutScheme = url.substring(schemeIndex + schemeSeparator.length) | |
} | |
else { | |
scheme = "https" | |
urlWithoutScheme = url | |
} | |
val pathWithQueryString = urlWithoutScheme.replace(authority, "") | |
val components = pathWithQueryString.split('?') | |
val queryWithFragment = if (components.size > 1) components.last() else "" | |
val subcomponent = queryWithFragment.split('#') | |
val authority = urlWithoutScheme.substring(0, urlWithoutScheme.indexOf('/')) | |
val path = components.firstOrNull() | |
val query = subcomponent.firstOrNull() | |
val fragment = if (subcomponent.size > 1) subcomponent.last() else "" | |
return URI(scheme, authority, path, query, fragment).toURL() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment