Using JavaScript methods in C#

I ran into a weird problem today.  I needed to escape a string in c# in such a way as to be able to unescape() it later with JavaScript into the original string.  JavaScript has an escape() method that is able to do this, but since I’m writing the code in C#, I can’t really access that method.  At first, I looked into HttpServerUtility.UrlEncode() and the HttpServerUtility.HtmlEncode() methods, but those are not equivalent to JavaScript’s escape() method. 

However, it seems Microsoft has put in a library which gives us access to JavaScript methods ( whether this is simply mimicking what JavaScript does or if it actually uses JavaScript… I could really care less).  All that was needed is a reference to Microsoft.JScript in the project, and I was able to call the Microsoft.JScript.GlobalObject.escape() method, and it produces the exact same output as the JavaScript version.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.