[英]Proper way to escape a string
我已经在JavaScript中为网站创建了“编辑评论”按钮。 实际上,一切正常,但字符串转义不起作用。 我只是想在编辑输入中输入类似
<script> alert(user->id); </script>
它显示警报!
我尝试执行以下类似的长时间转义,但它们没有改变任何内容,警报仍然出现:
newComment.replace("'","\'");
newComment.replace("\"","\\\"");
newComment.replace("(","\(");
newComment.replace(")","\)");
newComment.replace("<","\<");
newComment.replace(">","\>");
newComment.replace(";","\;");
我也尝试过使用encodeURI ,但是它疯狂地显示了编码的注释,看起来一点也不好...
那么,现在转义字符串的正确方法是什么? 我正在阅读数十个类似的话题,但我根本不明白这一点。
但是他们什么也没改变
newComment.replace("'","\'");
您对函数的结果不做任何事情。 相反,这样做
newComment = newComment.replace("'","\'");
同样,您可以将replace函数链接在一起,但是要确保对结果做一些事情,例如将其分配给变量,否则实际上什么也没做
newComment = newComment.replace("'","\'").replace(...).replace(...);
当必须在应用程序的源代码中编码该字符时,应使用转义字符。 它告诉解释器/编译器它不应该像一般字符一样对待该字符,而不是应该遵守该语言的语法规则的字符。 例如:
// JavaScript引擎会将其解释为错误,并且不会执行代码。
var newComment = 'test'';
//这样做:
var newComment = 'test\'';
\\告诉引擎“嘿,不要用它来关闭字符串,把它当作字符串的一部分。” 随着用户在运行时输入文本,引擎已经知道不应将其解释为源,而应将其解释为运行时值,因此在这种情况下无需对其进行转义。
关于此代码的注释:
newComment.replace("'","\'");
newComment.replace("\"","\\\"");
newComment.replace("(","\(");
newComment.replace(")","\)");
newComment.replace("<","\<");
newComment.replace(">","\>");
newComment.replace(";","\;");
newComment = newComment.replace('','');
那样进行更改和分配newComment = newComment.replace('','');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.