0

I have a UITextView in my Swift app in which users can input text. They can input text with as many line breaks as they like but I need to save the string with the newline command (\n). How would I do this?

For example, my user inputs

Line 1
Line 2
Line 3

in the UITextView. If I was to retrieve the string...

let string = textview.text!

this would return

"Line 1
Line 2
Line 3"

when I would like for it to return

"Line1\nLine2\nLine3"

How would I go about doing this? Can I use a form of replacingOccurrences(of:with:)? I feel like I'm missing a fairly obvious solution...

Jacob Cavin
  • 2,169
  • 3
  • 19
  • 47

2 Answers2

1

Eureka! After WAY too much research and learning all about String escapes, I found a very simple solution. I'm quite surprised that this isn't an answer out there already (as far as I can tell haha) so hopefully, this helps someone!

It's actually quite simple and this will work of any String you could be using.

textView.text!.replacingOccurrences(of: "\n", with: "\\n")

Explanation: Ok so as you can tell, it's quite simple. We want to replace the newline command \n with the string "\n". The problem is that if we replace \n with \n, it's just going to transfer over to a newline, not a string. This is why escapes are so important. As you can see, I am replacing \n with \\n. By adding an extra \ we escape the command \n entirely which turns it into a string.

I hope this helps someone! Have a great day!

Jacob Cavin
  • 2,169
  • 3
  • 19
  • 47
0

Have you tried replacing \r with \n? or even \r\n with \n?

I hope I am not making an obvious assumption you considered, but maybe this may come in handy: Is a new line = \n OR \r\n?

BassBoy
  • 15
  • 6
  • Hello! Thank you so much for your answer. Sadly, I have already tried this but to no avail. Thanks anyways, though! – Jacob Cavin May 31 '20 at 15:01