Search code examples
javascriptrhomobilerhodes

How to parse \n in string while passing the value to javascript


In my code, i need to pass the value present in instance variable to javascript, and then use that value to set onto textarea.

$('textarea.myclass').val('<%= @text_value %>');

But if the variable @text_value contains \n (this is\n demo) then, its leads to javascript error and the page shows exactly as this, separated by space in between,

$('textarea.myclass').val('this is 
   // error message over here 
demo');

Any way i can handle this ?


Solution

  • I also faced such situation, and i just escaped the \ to \\, so finally \n to \\n, \r to \\r

    $('textarea.myclass').val('<%= @text_value.gsub("\r","\\r").gsub("\n","\\n") %>');
    

    Hope this corrects you error too.