Generic way to Escape Quotes in Javascript Variable
I have a form where users can enter any HTML.
var title = "Cool <a href="http://google.com">Check This</a>"
As you can see, the variable is having "
but it can be also '
. It causes an error if开发者_StackOverflow there is "
. What is better way to fix this? Storing escaped string in database like below?
$title = str_replace('"', "'", $_REQUEST['title']); // Replace double quote with single quote as js variable above is wrapped with double quotes.
Or escape it before showing on page? Anything in jQuery like escape that can help here?
var title="Cool <a href=\"http://google.com\">Check This</a>"
Well, you cannot escape it using JavaScript because JavaScript needs to see what you want to escape and you want to escape that. If you use PHP, you can use addslashes()
prior to inserting into JavaScript.
Anyways, you should be careful of allowing to insert any HTML. Wrongly escaped HTML (like allowing to insert <script>
) can allow to do various dangerous stuff, like stealing all cookies.
精彩评论