I want to replace all the specific words in a string.
For example)
var str = "apple is red. apple is green"
I want to change background the word "apple" only in the sentence.
So I tried the following.
let resultString = NSMutableAttributedString(string: str)
let apple = NSMutableAttributedString(string: "apple")
apple.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.yellow, range: NSRange(location: 0, length: apple.length))
resultString.replaceCharacters(in: (str as NSString).range(of: "apple"), with: apple)
but result that.
resultString = "apple(change background color) is red. apple(did not change background color) is green"
I want result -> "apple(change background color) is red. apple(change background color) is green.
What should I do?