2

I want to insert, via RJS a multiline string taken from a textarea. Doing:

$('#description').text('<%= simple_format description %>');

does not work because it will generate something like this:

$('#description').text('<p>first line
<br />second line</p>

<p>fourth line</p>');

Because the string isnt on a single line, the JS call fails. So now that simple_format formatted the string correctly, how can I have it all print on a single line in my RJS file?

1
  • You need to JS-escape the string. Commented Nov 29, 2012 at 17:18

2 Answers 2

2

Try this:

$('#description').text('<%= simple_format(description).gsub("\n", "\\n").gsub("\r", "\\r").gsub("\t", "\\t").gsub("'","\\'")  %>');

This replaces the newline character with an escape sequence Javascript understands. Similarly for other characters like carriage-return and tab. Moreover it replaces the ' character which is a string delimiter character with an escape sequence for it so that a string such as "It's mine" does not cause any surprises.

Sign up to request clarification or add additional context in comments.

2 Comments

almost perfect, should have been simple_format(description).gsub("\n", "\\n").gsub("'","\\'")
@Alain: Thanks :-) I accidentally answered the question thinking this was an ASP.NET question and noticed the ruby-on-rails tag a few minutes later!!! During the past few minutes tried to learn enough Ruby to make it appropriate for the question, but ... Thanks :-) I will edit accordingly!
0

You could (preferably) use the built in escape_javascript() or j() methods:

$('#description').text('<%= j(simple_format(description)) %>');

http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.