webdeb
webdeb

Reputation: 13211

Escape string in elixir

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

Upvotes: 2

Views: 3747

Answers (2)

intentionally-left-nil
intentionally-left-nil

Reputation: 8274

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

Upvotes: 3

Scymex
Scymex

Reputation: 1074

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

Upvotes: 3

Related Questions