1

What is the simplest way to unescape the following string in Ruby.

Sample Input

str = "\\u003Cul id=\\\"list_example\\\"\\u003E\\n\\t\\u003Cli class=\\\"item_example\\\"\\u003EHello\\u003C/li\\u003E\\n\\u003C/ul\\u003E\\n\\n"
puts str # => \u003Cul id=\"list_example\"\u003E\n\t\u003Cli class=\"item_example\"\u003EHello\u003C/li\u003E\n\u003C/ul\u003E\n\n
str.encoding # => #<Encoding:UTF-8>

Desired Output

puts str #=>
<ul id="list_example">
  <li class="item_example">Hello</li>
</ul>

2 Answers 2

2

That string is escaped twice. There are a few ways to unescape it. The easiest is eval, though it is not safe if you don't trust the input. However if you're sure this is a string encoded by ruby:

print eval(str)

Safer:

print YAML.load(%Q(---\n"#{str}"\n))

If it was a string escaped by javascript:

print JSON.load(%Q("#{str}"))

See also Best way to escape and unescape strings in Ruby?

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

Comments

2

The simplest approach is just to read the string as a JSON string.

unescaped_str = JSON.load("\"#{str}\"")

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.