18

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")
4
  • Show how you "call this line of code again". That's where you're going wrong, after all. Commented Jan 21, 2015 at 4:23
  • textView.text = content.stringByReplacingOccurrencesOfString("<br /><br />", withString:"\r") textView.text = content.stringByReplacingOccurrencesOfString(" &nbsp;", withString:" ") Commented Jan 21, 2015 at 4:27
  • But there's the problem. You are starting over from the original content. The text view's text is overwritten because you are overwriting it! Commented Jan 21, 2015 at 4:45
  • @matt I understood this question to be asking if there's a way of replacing all the characters you want in one pass. i.e. textView.text = content.stringByReplacingOccurrencesOfString([",", ":", "\n", "\r"], withString "") Commented Feb 12, 2016 at 16:02

4 Answers 4

35

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
Sign up to request clarification or add additional context in comments.

3 Comments

This is great & exactly what I was looking for! Great use of RegEx, something I haven't used much in Swift. Thanks for the awesome answer Michael.
Could you explain - should I always use .regularExpression? What if I just need to specify a list of concrete symbols I need to replace/delete?
There may be other ways, however a regular expression is good way to represent a set of concrete characters. For example if I wanted to replace "A", "B", and "Z", the code would look like: x.replacingOccurrences(of: "[ABZ]", with: "7", options: .regularExpression, range: nil)
13

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

3 Comments

This is not an efficient solution, see my answer using CompareOptions.CompareOptions.regularExpression
@Michael But I guess this works in more generic cases. What if my strings aren't regular expressions? How would your answer change?
@KarthikKannan Are you referring to my answer below? Did you comment in the wrong answer? If so, please repeat the question in my answer to avoid confusion for others.
8

As @matt mentioned you are starting over with the same content string. The stringByReplacingOccurrencesOfString method doesn't actually change anything in the original content string. It returns to you a new string with the replacement changes while content remains unchanged.

Something like this should work for you

let result1 = content.stringByReplacingOccurrencesOfString("<br /><br />", withString:"\r") 
let result2 = result1.stringByReplacingOccurrencesOfString(" &nbsp;", withString:" ")
textView.text = result2

Comments

1
extension String {
    var html2AttributedString:NSAttributedString {
        return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!
    }
}

let myHtmlCode = "<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F}</style><span id=\"red\" >Red</span> <span id=\"green\" >Green</span><span id=\"blue\">Blue</span>"

myHtmlCode.html2AttributedString

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.