Will "the Mighty" Strohl

HOW TO: Escape Single Quotes for JavaScript Strings

While I was writing a class to allow me to quickly grab preformatted JavaScript functions (i.e., confirm, alert, etc.), I came across the need to ensure that a string passed into those methods would not throw a JavaScript error upon rendering.  This could possibly happen if the message contained singles quotes for contractions, quotes, etc.

So, I quickly set upon adding another method to a growing RegularExpress library class that I am working with.  Here is the method:


''' <summary>
''' EscapeSingleQuotes - this method allows you to pass a string into it to 
''' update your string with all single quotes escaped to prevent JavaScript errors
''' </summary>
''' <param name="TextToEscape">String - the text that you want to parse</param>
''' <remarks>
''' Use this method to make a string safe for JavaScript routines
''' </remarks>
Public Shared Function EscapeSingleQuotes(ByVal TextToEscape As String) As String
    ' create a new regex object
    Dim re As New Regex("(\w'|\s'|!'|@'|#'|\$'|%'|\^'|&'|\*'|\('|\)'|\-'|\+'|='|:'|;'|""'|,'|<'|\.'|>'|/'|\?'|\['|\]'|\{'|\}'|'')[^\']")

    ' get a collection of the instances of singles to escape     Dim reMatches As System.Text.RegularExpressions.MatchCollection = re.Matches(TextToEscape)

    ' loop through the matches and escape the single quotes     For i As Integer = 0 To reMatches.Count - 1         ' update the single quote with a preceding backslash         TextToEscape = TextToEscape.Replace(reMatches.Item(i).Value, reMatches.Item(i).Value.Replace("'", "\'"))     Next

    Return TextToEscape End Function


It is just that easy.  Now all I have to do is to write something like this to take advantage of it:

Dim strString As String = _
    "This is a 'sample' this one \' is escaped, and this one " & _
    "$' !' -' has different puncuation preceding it, and " & _
    "don't forget double single '' quotes"
strString = EscapeSingleQuotes(strString)

Which would return a string like this:

This is a \'sample\' this one \' is escaped, and this one 
$\' !\' -\' has different puncuation preceding it, and
don\'t forget double single \'\' quotes

Notice that it escaped all of the single quotes EXCEPT the single quote that was already escaped.  Have fun!

blog comments powered by Disqus