Below is the following line of code I use to replace an HTML break tag with a carriage return. However, I have other HTML symbols that I need to replace and when I call this line of code again, with different parameters, it's as if the first one is overwritten. Is there a way I can include multiple parameters? Is there a more efficient way to do this in Swift? For example: replace both br> with "" and nbsp with "".
textView.text = content.stringByReplacingOccurrencesOfString("<br /><br />", withString:"\r")
In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.
Swift String dropLast() The dropLast() method removes the last character of the string.
Swift strings can be treated as an array of individual characters. So, to return the length of a string you can use yourString. count to count the number of items in the characters array.
Use replacingOccurrences along with a the String.CompareOptions.regularExpresion option.
Example (Swift 3):
var x = "<Hello, [play^ground+]>"
let y = x.replacingOccurrences(of: "[\\[\\]^+<>]", with: "7", options: .regularExpression, range: nil)
print(y)
Input characters which are to be replaced inside the square brackets like so [\\ Characters]
Output:
7Hello, 7play7ground777
I solved it based on the idea of Rosetta Code
extension String {
func stringByRemovingAll(characters: [Character]) -> String {
return String(self.characters.filter({ !characters.contains($0) }))
}
func stringByRemovingAll(subStrings: [String]) -> String {
var resultString = self
subStrings.map { resultString = resultString.stringByReplacingOccurrencesOfString($0, withString: "") }
return resultString
}
}
Example:
let str = "Hello, stackoverflow"
let chars: [Character] = ["a", "e", "i"]
let myStrings = ["Hello", ", ", "overflow"]
let newString = str.stringByRemovingAll(chars)
let anotherString = str.stringByRemovingAll(myStrings)
Result, when printed:
newString: Hllo, stckovrflow
anotherString: stack
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With