Jacob Cavin
Jacob Cavin

Reputation: 2319

Save UITextView String With \n Instead of Line Breaks (Swift)

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...

Upvotes: 0

Views: 1185

Answers (2)

Jacob Cavin
Jacob Cavin

Reputation: 2319

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!

Upvotes: 1

BassBoy
BassBoy

Reputation: 15

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?

Upvotes: 0

Related Questions