Encode C# string as JavaScript syntax

Neo 421 Reputation points
2023-04-28T05:08:26.22+00:00

Is there any ready-to-use function in C#/.NET to encode a plain string to JavaScript syntax?

For example, I am utilizing WebView2 to do some automation work. When I call WebView2.ExecuteScriptAsync, I need to pass string data which need to be encoded in JavaScript syntax.

Currently I invented my own wheel which works fine:

        public static string EscapeForScript(this string script)
        {
            return script.Replace(@"\", @"\\").Replace("'", @"\'").Replace("\"", @"\""");
        }

var textScript = this.scriptEdit.Text.EscapeForScript();
            var callScript = $"set_input_text('{textScript}')";
            await this.webView.ExecuteScriptAsync(callScript);
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-04-28T05:28:19.9933333+00:00

    There is a HttpUtility.JavaScriptStringEncode function, but in modern applications, which use the System.Text.Json library, try this too:

    string result = JsonEncodedText.Encode( input ).ToString( );
    // or
    string result = Encoding.UTF8.GetString( JsonEncodedText.Encode( input ).EncodedUtf8Bytes );
    // or
    string result = JsonEncodedText.Encode( input, JavaScriptEncoder.UnsafeRelaxedJsonEscaping ).ToString( );
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.