简体   繁体   English

使用JavaScript转义单引号

[英]Escape single quote with JavaScript

I am aware with escaping special characters in HTML. 我知道在HTML中转义特殊字符。

But, I am still asking this as I have come across a situation. 但是,我遇到这样的情况时仍在问这个问题。

I have a JSP, in which I am not allowed put validation on input. 我有一个JSP,不允许在其中输入验证信息。 Users are entering special characters to test. 用户正在输入特殊字符进行测试。

Input string: 输入字符串:

'#@$% “#@ $%

When I am displaying from database, I am using 从数据库显示时,我正在使用

<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>

where "map" is an array of Hashmap. 其中“ map”是Hashmap的数组。 This works fine. 这很好。

The problem comes when I need to pass this string to JavaScript using 当我需要使用以下方法将此字符串传递给JavaScript时,问题就来了

<input type="Button"
onclick="onEdit('<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>',
'<%= strShortCut%>','<%= map[i].get("uid")%>')" value="Edit">

The string becomes ''#@$%' . 字符串变为''#@$%'

How do I escape a single quote? 如何转义单引号?

If you would be using Java, maybe you can do the below in Java. 如果要使用Java,则可以使用Java进行以下操作。

import org.apache.commons.lang.StringEscapeUtils;
...

String result = StringEscapeUtils.escapeJavaScript(jsString);

Just prepend every single quote with a backslash. 只需在每个单引号前加一个反斜杠即可。 Like the following: StringEscapeUtils.escapeHtml(map[i].get("text").toString()).replace("\\'","\\\\'") 类似于以下内容:StringEscapeUtils.escapeHtml(map [i] .get(“ text”)。toString())。replace(“ \\'”,“ \\\\'”)

But your problem is not only in the single quote. 但是,您的问题不仅在于单引号。 There is also the double quote (") and the backslash itself (\\). 还有双引号(“)和反斜杠本身(\\)。

Use the same technique as shown before. 使用与之前所示相同的技术。 You can also use regular expressions , but I showed you the simplest way. 您也可以使用正则表达式 ,但是我向您展示了最简单的方法。

To check the escape characters, look at the URL http://docs.oracle.com/javase/tutorial/java/data/characters.html . 要检查转义字符,请查看URL http://docs.oracle.com/javase/tutorial/java/data/characters.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM