go

How to escape the html using golang?


The html text following:

<script type="text/javascript">alert(123);</script>
<script>alert(123);</script>

As mentioned above, only part of html text was escaped.

Now, I want to escape the text: <script>alert(123);</script>.

Expected result:

&lt;script type=&#34;text/javascript&#34;&gt;alert(123);&lt;/script&gt;
&lt;script&gt;alert(123);&lt;/script&gt;

I need some help.


Solution

  • There's the EscapeString function in the html package

    import "html"
    
    // ...
    
    unescaped := `<script>alert(123);</script>`
    escaped := html.EscapeString(unescaped)