Escaping Javascript in Perl

I found this page really useful for escaping stuff to pass to javascript functions in PHP, and I needed a perl version.

So here it is:

sub js_enc {
    my $str = shift || '';
    my @chars = split(//,$str);
    foreach my $c (@chars) {
        $c = '\x' . sprintf("%x", ord($c));
    }
    return join('',@chars);
}

2 thoughts on “Escaping Javascript in Perl

  1. Some weirdness in the post:

    The sourcecode in the above example gets all whacked with the smart quotes and curly quotes and all that – if you just copy/paste the source, you’ll get all sorts of errors from Perl.

    Secondly, spaces and tabs seem to act funky when I tried this – I’m trying to escape some HTML in Perl to pass to FCKEditor which itself is being called by HTML::Template – anyways, here’s what I did – after escaping the HTML, I think unescaped spaces and tabs – I bet it would be easier to do this using HTML::Entities but, meh:

    sub js_enc {

    my $str = shift || ”; my @chars = split(//,$str); foreach my $c (@chars) { $c = ‘\x’ . sprintf(“%x”, ord($c)); } my $e = join(”,@chars);

    $e =~ s/\xa/ /g; $e =~ s/\x9/\t/g; return $e;

    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">