2010-11-05 13 views
2

Je dois écrire une fonction VBScript qui peut convertir des chaînes arbitraires en une chaîne que je peux utiliser en toute sécurité dans JavaScript. Quelque chose comme ceci:Fonction de conversion d'une chaîne arbitraire à utiliser dans JavaScript

"Hello World" 
-- becomes -- 
"Hello World" 

"Hello 
World" 
-- becomes -- 
"Hello\nWorld" 

"Hello 
    World" 
-- becomes -- 
"Hello\n\tWorld" 

"Hello'World" 
-- becomes -- 
"Hello\'World" 

-je utiliser la fonction comme ceci:

var foo = '<p><%= thatfunction(Recordset("TextField")) %></p>'; 

J'espère que vous avez obtenu le point. La fonction ne doit pas être pare-balles mais proche.

Répondre

2

@Salman A: Voici une fonction ASP classique, vous pouvez utiliser

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 
+0

Ce sont les "autres" valeurs qui m'inquiètent :) –

+0

@Salman A: Jetez un coup d'oeil à http://www.the-art-of-web.com/javascript/escape/#section_2 - vous pourrait probablement faire quelque chose de similaire pour ASP classique en utilisant 'Server.HTMLEncode' et' Server.URLEncode' pour comparer les sorties. Cela devrait prendre soin des "autres" valeurs. :-) – stealthyninja

0

Vous pouvez utiliser JavaScriptSerializer

Dim serializer as New JavaScriptSerializer() 
Dim jsString as String = serializer.Serialize(your_string_here); 

... mais votre exemple montre le texte étant intégré dans un élément HTML - pas dans une chaîne Javascript. Peut-être que vous cherchez HttpUtility.HtmlEncode(). Votre exemple pourrait alors ressembler à ceci:

<p><%= HttpUtility.HtmlEncode(Recordset("TextField")) %></p> 
+1

J'ai modifié un peu la question. J'ai besoin d'une solution classique asp/vbscript. –