Skip to content

Instantly share code, notes, and snippets.

@emin-grbo
Created December 4, 2024 13:46
Show Gist options
  • Save emin-grbo/742ae4ac9268ec832cb4aff751bc2812 to your computer and use it in GitHub Desktop.
Save emin-grbo/742ae4ac9268ec832cb4aff751bc2812 to your computer and use it in GitHub Desktop.
import Foundation
extension String {
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - returns: percent-escaped string.
public func encoded() -> String {
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment