How do I escape a Unicode string with Ruby?

前端 未结 6 906
春和景丽
春和景丽 2020-12-14 22:10

I need to encode/convert a Unicode string to its escaped form, with backslashes. Anybody know how?

6条回答
  •  无人及你
    2020-12-14 22:55

    If you have Rails kicking around you can use the JSON encoder for this:

    require 'active_support'
    x = ActiveSupport::JSON.encode('µ')
    # x is now "\u00b5"
    

    The usual non-Rails JSON encoder doesn't "\u"-ify Unicode.

提交回复
热议问题