Reputation: 272296
I need to write a VBScript function that can convert arbitrary strings into a string that I can safely use inside JavaScript. Something like this:
"Hello World"
-- becomes --
"Hello World"
"Hello
World"
-- becomes --
"Hello\nWorld"
"Hello
World"
-- becomes --
"Hello\n\tWorld"
"Hello'World"
-- becomes --
"Hello\'World"
I need to use the function like this:
var foo = '<p><%= thatfunction( Recordset( "TextField" ) ) %></p>';
I hope you got the point. The function does not have to be bullet-proof but close.
Upvotes: 2
Views: 686
Reputation: 10371
@Salman A: Here's a Classic ASP function you could use
Function thatfunction(ByRef input_string)
If NOT IsNull(input_string) AND input_string <> "" Then
Dim working_string
working_string = input_string
working_string = Replace(working_string, vbNewLine, "\n")
working_string = Replace(working_string, vbTab, "\t")
working_string = Replace(working_string, "'", "\'")
' .. other escape values/strings you may wish to add
thatfunction = working_string
End If
End Function
Upvotes: 2
Reputation: 13542
You can use JavaScriptSerializer
Dim serializer as New JavaScriptSerializer()
Dim jsString as String = serializer.Serialize(your_string_here);
... but your example shows the text being embedded in an HTML element--not in a Javascript string. Maybe you're looking for HttpUtility.HtmlEncode(). Your example might then look like this:
<p><%= HttpUtility.HtmlEncode( Recordset( "TextField" ) ) %></p>
Upvotes: 0