I currently have the following code (jQuery) in my view, and when title has a \n character then it breaks my js.
$("#t").html("#{title.html_safe}");
The following works but I think it’s somewhat a hack:
$("#t").html("#{title.gsub("\n","")}");
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The method you are looking for is String#chomp. It will remove any carriage return characters from the end of your string.
As always, only use
html_safeif you are completely sure thetitlevariable is safe… especially since you are using it within a Javascript file! I did not include it in my code example because I just couldn’t bring myself to do it. Plus, see the note on APIdock in regards to usinghtml_safeon a variable that could benil. I would suggest only using it on a string literal.EDIT:
If there is a chance that your
titlemay contain quotes that need to be escaped before used in Javascript (for instance'"Winter is Coming", I say'which will interpolate into your javascript as.html(""Winter is Coming", I say");) then you should also use theescape_javascriptmethod as suggested in the link @mu is too short provided.If
title = '"Winter is Coming"'then the above code would produce.If there is also a chance that there is a carriage return in the middle of the title string, then
String#gsubis the way to go.I put a space in the second parameter of
gsubso'Winter\nis\nComing'would become'Winter is Coming'and not'WinterisComing'.