Replace line break in string


Using ruby on rails I’m creating a string on the fly, which I would like to output using JavaScript.

Unfortunately the string contains line breaks and I am getting the error message:
“unterminated string literal”

Is there any way to do something like this in JavaScript:

var myString = 'A string with
 line breaks'.sub("\

#=> A string without line breaks

The reason I want to use JavaScript to output this string is that it should only appear when JavaScript is enabled (I have a nice alternative for when JavaScript is turned off).

Is there any other way to do this?

Something like:
<script><p>JS is on</p></script>
<noscript><p>JS is off</p></noscript>
would be ideal.

I suppose I could write something like:

<%= strip_returns(collection_select … &div_to_update='+‘memb1’" )}"}) %>

That might work.

But I quite like the solution I came up with, hiding the element by default and using JS to display it again.

It’s being produced by a form helper.
The code is:

<%= collection_select("applicant", :topic_1,  @topics,  :topic, :topic,
{:prompt   => "Select a Topic"},
{:onchange => "#{remote_function(:url  => {:action => "update_members"},
:with => "'topic_name='+value+'&partial_to_render='+'member_1'+'&div_to_update='+'memb1'" )}"}) %>

By default the forms helper ‘collection_select’ produces a select tag with line breaks.

To sub them out server side, I’d have to go hacking about somewhere in the Module ActionView::Helpers::FormOptionsHelper. Which would be a bit of a pain in the neck.

If it’s being produced on the fly, there must be some sort of interaction between the Server and Client. That or your using Ajax to load an external script, in which case, you cannot do anything about it.


Thanks for the reply.

I’d reached the same conclusion as you, but unfortunately as the string is being produced on the fly, a server-side solution would be difficult to implement.

I did solve the problem another way however.
I added “display:none” to the element being generated and then used JavaScript to change that back to “display:inline”.

This means that you can see the element when JS is on, and it is invisible when JS is disabled, which was exactly my goal.

since it’s server side code, can’t you simply write a function that would replace the new lines and instead of using something like ‘+value+’ you could use ‘+functionName(value)+’

Javascript won’t help you here. The code wouldn’t execute because the line-breaks are causing the compiler/engine to fail.

I’ve had this before and the only way I’ve managed to resolve it is to use server side code to replace them with something else.