I have JavaScript code that looks like the following:
foo.replace(/(\r\n|\n|\r)/gm, "");
Basically this strips any return carriages and new lines from my string. I'd like to do something similar in Swift 3.
I see func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = default, range searchRange: Range<Index>? = default) -> String
is available. The problem is, this only takes one string in the of
parameter.
Does this mean I need to call the method multiple times for each of my instances above, once for \r\n
, once for \n\
and once for \r
? Is there anyway to potentially accomplish something closer to what the regex is doing instead of calling replacingOccurrences
three times?
Use replacingOccurrences
with the option set to regularExpression
.
let updated = foo.replacingOccurrences(of: "\r\n|\n|\r", with: "", options: .regularExpression)
To replace non-digits you can use "\D" as a regular expression
let numbers = "+1(202)-505-71-17".replacingOccurrences(of: "\\D", with: "", options: .regularExpression)
You can find how to use other regular expressions here
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