1

I have a user enter a multi string in an NSTextView.

var textViewString = textView.textStorage?.string

Printing the string ( print(textViewString) ), I get a multi-line string, for example:

hello this is line 1 

and this is line 2

I want a swift string representation that includes the new line characters. For example, I want print(textStringFlat) to print:

hello this is line 1\n\nand this is line 2

What do I need to do to textViewString to expose the special characters?

Kenneth
  • 1,035
  • 1
  • 12
  • 26
  • 1
    Replace `\n` with `\\n`. But that only handles the newlines. What other special characters do you want to handle? – rmaddy Aug 23 '18 at 22:25
  • Oh, duh! Thanks! My brain wasn't working there for a second. If you want to write that as an answer, I will approve as correct. – Kenneth Aug 23 '18 at 22:26
  • https://stackoverflow.com/questions/43484860/how-to-print-escape-sequence-characters-in-swift (there is an answer showing also all the escaped sequences if needed). – Larme Aug 24 '18 at 10:22

1 Answers1

3

If you just want to replace the newlines with the literal characters \ and n then use:

let escapedText = someText.replacingOccurrences(of: "\n", with: "\\n")
rmaddy
  • 314,917
  • 42
  • 532
  • 579