2

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.

2 Answers 2

2

@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
Sign up to request clarification or add additional context in comments.

2 Comments

It is the "other" values that I'm worried about :)
@Salman A: Have a look at the-art-of-web.com/javascript/escape/#section_2 -- you could probably make something similar for Classic ASP using Server.HTMLEncode and Server.URLEncode to compare the outputs. This should take care of the "other" values. :-)
0

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>

1 Comment

I've modified the question a bit. I need classic asp/vbscript solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.