我需要在JavaScript中從用戶提供的一些文本創建一個字符串。當我嘗試運行此行時:是否有避免未終止的字符串文字錯誤,如果我從一個未知的來源創建一個字符串
var str = new String('<%= @note.text %>')
我得到未終止的字符串文字錯誤。鑑於我無法控制輸入的內容,並且我無法指定字符串開始進行任何字符替換,我該如何解決此問題?謝謝閱讀。
我需要在JavaScript中從用戶提供的一些文本創建一個字符串。當我嘗試運行此行時:是否有避免未終止的字符串文字錯誤,如果我從一個未知的來源創建一個字符串
var str = new String('<%= @note.text %>')
我得到未終止的字符串文字錯誤。鑑於我無法控制輸入的內容,並且我無法指定字符串開始進行任何字符替換,我該如何解決此問題?謝謝閱讀。
沒有什麼可以做客戶端的,你需要清理服務器上的字符串。鑑於你正在通過<%=%>將字符串放入字符串構造函數,我假設你正在使用各種ASP.Net。
我確定有一個更優雅的方法來做到這一點,但這應該作爲第一次編碼字符串以用於JavaScript。這並沒有試圖解決首先將任意字符串傳遞給JavaScript的相對優點。 (在大多數情況下,應該有很大可能是惡意字符串一些服務器端的檢查。)
假設需要注意的是文本輸入字段,這樣的事情可能會奏效....
// New Property in your code behind
public string outputText {get; private set;}
在的OnLoad(),添加
// Encode the string
string tempText = Note.Text
outputText = String.empty;
foreach(char character in tempText)
{
// Prefix quotation mark with a backslash,
if(char == "\"")
outputText += "\\\"";
// Prefix apostrophe with a backslash,
else if(char == "'")
outputText += "\\'";
// convert newline to a literal.
else if(char == "\n")
outputText += "\\n";
else
outputText += character;
}
最後,在.aspx
var str = new String('<%= outputText %>')
你不能向JS中扔任意文本,並且能夠從錯誤中恢復。
您必須在將數據放入文檔之前對數據進行清理。我不知道爲什麼你認爲你不能這樣做,但你需要消除任何阻礙它的障礙。