5

I have this line in a javascript block in a page:

res = foo('<%= @ruby_var %>'); 

What is the best way to handle the case where @ruby_var has a single-quote in it? Else it will break the JavaScript code.

7 Answers 7

11

I think I'd use a ruby JSON library on @ruby_var to get proper js syntax for the string and get rid of the '', fex.:

res = foo(<%= @ruby_var.to_json %>)

(after require "json"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templating language)

(on the other hand, if JSON ever changed to be incompatible with js that'd break, but since a decent amount of code uses eval() to eval json I doubt that'd happen anytime soon)

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

2 Comments

Rails already comes with String#to_json, so you don't even need to include any libraries: api.rubyonrails.com/classes/Object.html#M000022
.to_json adds html quotes(&quot;) to my string
8

Rails has method specifically dedicated to this task found in ActionView::Helpers::JavaScriptHelper called escape_javascript.

In your example, you would use the following:

res = foo('<%= escape_javascript @ruby_var %>');

Or better yet, use the j shortcut:

res = foo('<%= j @ruby_var %>');

Comments

2
@ruby_var.gsub(/[']/, '\\\\\'')

That will escape the single quote with an apostrophe, keeping your Javascript safe!

Also, if you're in Rails, there are a bunch of Javascript-specific tools.

2 Comments

What if there was a \ already in the code? You need to escape \ before you escape '.
yeah, to handle bentilly's case you need: @ruby_var.gsub(/['\\]/, '\\\\\0')
2

Could you just put the string in a double-quote?

res = foo("<%= @ruby_var %>"); 

1 Comment

but then what if @ruby_var has a double quote in it?
2

You can also use inspect assuming you know it'll be a single quote:

res = foo(<%= @ruby_var.inspect %>);

Comments

0

I don't work with embedded Ruby too much. But how about using p (which invokes inspect) instead of <%= which might be doing something like print or puts. p always prints the string as if it were code wrapped in double quotes:

>> p "String ' \" String"
"String ' \" String"
# => nil  
>> p 'alpha " \' alpha'
"alpha \" ' alpha"
# => nil  

Comments

0

You may want to use the following first property, to get rid of the " from your string and then you can go ahead and use your json function.

res = foo('<%= @ruby_var %>.first'); 

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.