简体   繁体   中英

Escape double quotes and other special characters in js

I have something like in java

stringBuffer.append("<a onclick=\"javascript:setPName('"+StringEscapeUtils.escapeJavaScript(tmpResult)+"');\"><small> "+StringEscapeUtils.escapeJavaScript(tmpResult)+"</small></a>");

While checking the same on Console of Firebug it comes correctly. But I get the following when I check from IE developer tools:

<A onclick="javascript:setPName('TEST\\" AKHIL?);?><SMALL>TEST\\"AKHIL</SMALL></A>

Problem is that browser is not still recognizing it. I had used StringEscapeUtils.escapeJavaScript to escape single quotes but it does not work for double quotes.

The problem is that you are using " characters in an HTML attribute value delimited with the same character.

onclick="javascript:setPName('TEST\" <!-- attribute value ends here -->

The JavaScript is irrelevant.

You need to escape for HTML ( &quot; ) not JS.

You could avoid the problem entirely by writing unobtrusive JavaScript .

Change ['] to ["], try and see. (Please remove "javascript:")

stringBuffer.append("<a onclick=\"setPName(\""+StringEscapeUtils.escapeJavaScript(tmpResult)+"\");\"><small> "+StringEscapeUtils.escapeHtml(tmpResult)+"</small></a>");

Or set the value into attribute (param).

stringBuffer.append("<a param=\""+StringEscapeUtils.escapeHtml(tmpResult)+"\" onclick=\"setPName(this.getAttribute('param'))\"><small> "+StringEscapeUtils.escapeHtml(tmpResult)+"</small></a>");

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.

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