Skip to content

Instantly share code, notes, and snippets.

@dagronf
Last active August 9, 2019 08:18
Show Gist options
  • Save dagronf/18bd95d8b7f8b6f2e519681f7599c87e to your computer and use it in GitHub Desktop.
Save dagronf/18bd95d8b7f8b6f2e519681f7599c87e to your computer and use it in GitHub Desktop.
Simple remove/replace characters in a swift string
import Foundation
extension String {
/// Returns a new string by removing any instances of the specified characters
///
/// - Parameter
/// - replacementChars: String containing the characters to replace
/// - Returns: a new string filtering out the specified characters
func removing(charactersIn replacementChars: String) -> String {
return self.filter { replacementChars.contains($0) == false }
}
/// Removes any instances of the specified characters
///
/// - Parameter
/// - replacementChars: String containing the characters to replace
/// - Returns: a new string filtering out the specified characters
mutating func remove(charactersIn replacementChars: String) {
self = self.removing(charactersIn: replacementChars)
}
/// Returns a new string by replacing any instances of the specified characters with a new character
///
/// - Parameters:
/// - charactersIn: String containing the characters to replace
/// - replacement: replacement character
func replacing(charactersIn replacementChars: String, with replacement: Character) -> String {
return String(self.map { replacementChars.contains($0) ? replacement : $0 })
}
/// Replaces any instances of the specified characters with a new character
///
/// - Parameters:
/// - charactersIn: String containing the characters to replace
/// - replacement: replacement character
mutating func replace(charactersIn replacementChars: String, with replacement: Character) {
self = self.replacing(charactersIn: replacementChars, with: replacement)
}
}
@dagronf
Copy link
Author

dagronf commented Jan 30, 2019

	let inputName = "This?is*a\"text<"

	let sanitizedName = inputName.replaceCharacters(from: "/\\:?%*|\"<>", with: "_")
	// sanitizedName = "This_is_a_text_"

	let filteredName = inputName.removeCharacters(from: "/\\:?%*|\"<>")
	// filteredName = "Thisisatext"

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