Reputation: 353
So I got this address 7 rue la Tour d'Auvergne
from an API request in AJAX.
But when I feed it to an input in my view or even just display it like this
get_adress.js.erb
alert('<%= @sellsy_address.address %>')
$('#address').val('<%= @sellsy_address.address unless @sellsy_address.blank? %>');
I got this 7 rue la Tour d'Auvergne
Any idea on how I can manage to keep the d'
as it is ? I tried to encode or decode it in different ways but no results.
Thanks in advance
EDIT
If I use raw of html_safe, my js.erb just does not load at all anymore
Upvotes: 0
Views: 104
Reputation: 10517
Try using html_safe
along with escape_javascript
(or j
), like this:
alert('<%= j @sellsy_address.address.html_safe %>');
Alternatively, you could skip j
but change single quotes to double quotes, like this:
alert("<%= @sellsy_address.address.html_safe %>");
If I use raw of html_safe, my js.erb just does not load at all anymore
That is because you get a syntax error due to the '
in 7 rue la Tour d'Auvergne
being inside single quotes. Check the following examples;
Single quotes, without escape_javascript
(or j
)
alert('<%= @sellsy_address.address.html_safe %>');
//generated code:
alert('7 rue la Tour d'Auvergne');
As you can see, the alert gets the string '7 rue la Tour d'
and then expects a closing parenthesis ()
), so you get an error an no alert is displayed.
Single quotes, with escape_javascript
(or j
)
alert('<%= j @sellsy_address.address.html_safe %>');
//generated code:
alert('7 rue la Tour d\'Auvergne');
Now the '
has been escaped and is no longer a closing quote, so the alert is correctly displayed.
Double quotes, without escape_javascript
(or j
)
alert("<%= @sellsy_address.address.html_safe %>");
//generated code:
alert("7 rue la Tour d'Auvergne");
This time '
needs no escaping since the string is enclosed between double quotes ('" "') which avoids any conflict with single quotes ('
).
Upvotes: 2