What is the simplest way to unescape the following string in Ruby.
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>
puts str #=>
<ul id="list_example">
<li class="item_example">Hello</li>
</ul>
最简单的方法是将字符串作为JSON字符串读取。
unescaped_str = JSON.load("\"#{str}\"")
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}"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.