Escape quotes in JavaScript
I'm outputting values from a database (it isn't really open to public entry, but it is open to entry by a user at the company -- meaning, I'm not worried about XSS.)
I'm trying to output a tag like this:
<a href="" onclick="DoEdit('DESCRIPTION');">Click Me</a>
DESCRIPTION is actually a value from the database that is something like this:
Prelim Assess "Mini" Report
I've tried replacing " with ", but no matter what I try, Firefox keeps chopping off my JavaScript call after the space after the word Assess, and it is causing all sorts of issues.
I must bemissing the obvious answer, but for the life of me I can't figure it out.
Anyone care to point out my idiocy?
Here is the entire HTML page (it will be an ASP.NET page eventually, but in order to solve this I took out everything else but the problem code)
<html>
<body>
<a href="#" onclick="DoEdit('Preliminary Assessment "Mini"'); return false;">edit</a>
</body>
</html>
You need to escape the string you are writing out into DoEdit
to scrub out the double-quote characters. They are causing the onclick
HTML attribute to close prematurely.
Using the JavaScript escape character, , isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation,
"
.
"
would work in this particular case, as suggested before me, because of the HTML context.
However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
'
becomes x27
"
becomes x22
So your onclick would become:
DoEdit('Preliminary Assessment x22Minix22');
This would work for example also when passing a JavaScript string as a parameter to another JavaScript method ( alert()
is an easy test method for this).
I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.
<html>
<body>
<a href="#" onclick="DoEdit('Preliminary Assessment "Mini"'); return false;">edit</a>
</body>
</html>
应该做的伎俩。
链接地址: http://www.djcxy.com/p/12114.html上一篇: Java中的资源,URI,URL,路径和文件有什么区别?
下一篇: 在JavaScript中转义引号