Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 Escaping string for new line (String Encoding)

I am trying to escape string for new line i.e \n. For example lets say string is:-

First Line Of String
second Line of String
Third Line of String

Now if i use String extension and say

func escapeString() -> String{
newString =   self.stringByRemovingPercentEncoding
return newString
}

This extension does not give me newString as

First Line Of String\nSecond Line Of String\nThird Line Of String

I need above string as a jsonString to pass to server.i.e. i have to String encode it

like image 880
Mann Avatar asked Jul 03 '26 22:07

Mann


2 Answers

Swift 5

You can use JSONEncoder to escape \n, \, \t, \r, ', " and etc. characters instead of manually replacing them in your string e.g.:

extension String {
    var escaped: String {
        if let data = try? JSONEncoder().encode(self) {
            let escaped = String(data: data, encoding: .utf8)!
            // Remove leading and trailing quotes
            let set = CharacterSet(charactersIn: "\"")
            return escaped.trimmingCharacters(in: set)
        }
        return self
    }
}

let str = "new line - \n, quote - \", url - https://google.com"
print("Original: \(str)")
print("Escaped: \(str.escaped)")

Outputs:

Original: new line - 
, quote - ", url - https://google.com
Escaped: new line - \n, quote - \", url - https:\/\/google.com

like image 117
iUrii Avatar answered Jul 06 '26 19:07

iUrii


stringByRemovingPercentEncoding is for percent encoding as used in URLs, as you might expect from the name. (If not from that, maybe from reading the docs, the pertinent part of which even shows up in Xcode code completion.) That is, it takes a string like "some%20text%20with%20spaces" and turns it into "some text with spaces".

If you want to do a different kind of character substitution, you'll need to do it yourself. But that can still be a one-liner:

extension String {
    var withEscapedNewlines: String {
        return self.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
    }
}

Note the first argument to self.stringByReplacingOccurrencesOfString is an escape code passed to the Swift compiler, so the actual value of the argument is the newline character (ASCII/UTF8 0x0A). The second argument escapes the backslash (in the text passed to the Swift compiler), so the actual value of the argument is the text \n.

like image 35
rickster Avatar answered Jul 06 '26 19:07

rickster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!