2010-11-05 33 views
2

我需要編寫一個VBScript函數,可以將任意字符串轉換爲一個字符串,我可以安全地在JavaScript中使用。事情是這樣的:函數來轉換JavaScript中使用的任意字符串

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

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

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

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

我需要使用的功能是這樣的:

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

我希望你得到了點。該功能不一定是防彈的,但很接近。

回答

2

@Salman A:這是你可以使用

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

這是我擔心的「其他」值:) – 2010-11-06 05:44:18

+0

@Salman A:看看http://www.the-art-of-web.com/javascript/escape/#section_2 - 你可能會使用'Server.HTMLEncode'和'Server.URLEncode'來比較輸出,從而爲傳統的ASP做類似的事情。這應該照顧「其他」的價值。 :-) – stealthyninja 2010-11-08 14:48:29

0

您可以使用JavaScriptSerializer

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

...但你的例子顯示了被嵌入在HTML元素中的文本 - 不是在一個JavaScript字符串。也許你正在尋找HttpUtility.HtmlEncode()。然後,您的例子可能是這樣的:

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

我修改的問題有點傳統的ASP功能。我需要經典的asp/vbscript解決方案。 – 2010-11-05 10:12:46

相關問題