Is there a way to automatically format a string
for literal insertion into JavaScript code?
Say you have this in your page:
<script type="text/javascript">
var strvar = <asp:Literal runat="server" id="ltrStrvar"></asp:Literal>;
</script>
And in your server-side code:
protected void Page_Load(object sender, EventArgs e) {
ltrStrvar.Text = "hello \"world\"";
}
Is there a way to automatically have it escape the string and surround it with quotes for error-free insertion into JavaScript, so all I have to do is set the Text
property with an arbitrary string? I know how to do it manually but was looking for a more elegant solution.
您可以创建一个自定义的LiteralWithQuotationMarks
用户控件,该控件在内部使用Literal
控件并在缺少引号时将其括起来。
You could do something like this:
public string sanitizeJavascriptString(string dirtyInput)
{
return dirtyInput.Replace("\\", "\\\\")
.Replace("\"", "\\\"")
.Replace("'","\\'");
}
I don't know if there is an existing escape function, but I doubt it. I'm also not 100% sure what else needs to be escaped, but I assume you can add the other characters if you know what they are.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.