What's the right way to escape a string that will be encased in quotes and then handed off to a parser of some kind?
I'm generating some javascript and I want to be confidant that my quotes won't be out of whack. Here's an example of what I do not want to do.
sub alert { my $mesg = shift; print "alert('$mesg')\n"; } alert("Don't do that!");
The "'" in "Don't" will make the resulting javascript broken.
The obvious wrong solution is to replace "'" with "\'", but that would fail if I tried to be smart and called alert("Don\'t do that!") because it would turn it into "alert('Don\\'t do that)".
So, my question to you Monks is, what is the right way?
Update:
Waitaminute.. am I overthinking this..? Will
work?sub quote { my $str = shift; # escape all slashes $str =~ s/\\/\\\\/g; # escape all single-quotes $str =~ s/'/\\'/g; return $str; }
In reply to Quote Escape by pileofrogs
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |