2

Given a String like str = “\“ and then rendering it into some other program like JS or Python:

# index.js.eex
console.log(„<%= str %>“)

# hello.py.eex
print(„<%= str %>“)

results in console.log(„\“)

You see the problem the backslash will escape the closing quote and produce a syntax error in JS

The question is, How should I fix it?

PS: I am writing it on a mobile phone, so the quotes are not correct, will fix it as soon I am on my laptop

2 Answers 2

3

You can "javascript encode" the string in elixir.

The rules for JS are that a slash needs to be double-escaped. You can do that yourself, or use something like Phoenix.HTML.javascript_escape

javascript_escape("my string with \")

See the source code here if interested

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

2 Comments

python has different encoding rules, and so you would need a different format. If you are trying to get a string that works across many programming languages, it's better to treat it as data (such as JSON) and then import that into the appropriate code
This has been renamed Phoenix.HTML.javascript_escape/1 in latest versions.
3

If you are using Phoenix you might find these useful https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#escape_javascript/1 https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#html_escape/1

Or perhaps convert it to JSON and skip the quotes. Here's an example.

# index.js.eex
console.log(<%= raw(Jason.encode!(str)) %>)

Perhaps a view helper would be better (example for Phoenix):

defmodule MyAppWeb.LayoutView do
  use MyAppWeb, :view

  def raw_json(data) do
    case Jason.encode(data) do
      {:ok, result} -> raw(result)
      {:error, _reason} -> nil # Depending on what fallback you want
    end
  end
end

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.