在JavaScript中转义动态字符串 [英] Escape dynamic strings in JavaScript

查看:77
本文介绍了在JavaScript中转义动态字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在论坛程序中编写用于签名功能的脚本,每当有人在其中输入引号或其他JavaScript可解析字符时,它就会破坏我的程序。

I'm writing a script for a signature function in a forum program and any time someone puts a quote or some other JavaScript parse-able character into it, it breaks my program.

是否有一种方法可以强制JavaScript在不将其解析为脚本的情况下将其识别为字符串,或者失败了,该函数将动态字符串中的所有脚本都转义了?

Is there a way either to force JavaScript to recognize it as a string without parsing it as script or, failing that, a function that escapes all scripting within a string that will be dynamic?

我进行了一次搜索,发现无休止的网页上有关于如何用斜杠转义单个字符的信息-也许我的搜索技能需要工作。

I did a search and all I could find were endless webpages on how to escape individual characters with a slash - perhaps my search skills need work.

推荐答案

您是否使用服务器端语言动态地将签名的内容放入JavaScript字符串文字中?那可能不是最好的选择。您可能要重新考虑您的操作方式。

Are you putting the contents of the signature using a server-side language, dynamically, in a JavaScript string literal? That probably isn't the best way to go; you may want to reconsider the way you are doing it.

例如,一种更好的方法是,您可以在页面上仅包含一个元素签名(不必在视觉上是截然不同的),然后获取该内容以在JavaScript运行时期间在脚本中使用。

For example, a better way to do it could be that you could just have an element on the page for the signature (which doesn't have to be visually distinct) and then get the contents of that for use in the script during JavaScript runtime.

如果您仍然想使用您要走的路线,可以用 \'(或 替换'如果在脚本中使用双引号的字符串,则将code>替换为 \ ),并替换 \n \\n ,用换行符转义符替换实际的换行符。

If you still wanted to take the route you are going, you could replace ' with \' (or " with \" if you are using double-quoted strings in your script) and replace \n with \\n, which replaces real newlines with newline escapes.

这篇关于在JavaScript中转义动态字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆