Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi

A bit off topic. I have a perl script that retrieves text stored inside a mysql database. This text is text that was retrieved from a textarea input field, thus the chances of having newlines is very possible.

I wish to use Perl to retrieve this text from a mysql db and then place it inside a javascript variable. However, the problem with viewing this text properly in a web browser, is a javascript problem and not a Perl one.

So my question basically comes down to, is there a way in javascript you can escape quotes and newlines? Something similar to Perl's $myhtml = qq{ };? If not, then my question becomes, how would I use perl to change any newlines (\n) to become line breaks (br) in html?

Thanks for taking your time to read this post.

Replies are listed 'Best First'.
Re: OT: Perl and Javascript - escaping newlines
by InfiniteSilence (Curate) on Feb 26, 2006 at 00:13 UTC
    how would I use perl to change any newlines (\n) to become line breaks (br) in html?
    perl -e "$foo = qq|this\nwill\nlook\ndifferent|; $foo=~s/\n/<br>/g; p +rint $foo;" this<br>will<br>look<br>different c:\Temp>

    Celebrate Intellectual Diversity

Re: OT: Perl and Javascript - escaping newlines
by ikegami (Patriarch) on Feb 26, 2006 at 00:09 UTC

    Does JavaScript have a chr function?

    my $string = ... from db ...; my $jscode = $string; $jscode =~ s/(\W)/ '" + chr(' . ord($1) . ') + "' /ge; $jscode =~ s/ \+ ""//g; $jscode = qq{"$jscode"};
    will produce
    "line1" + chr(13) + "line2" + chr(13)
    for
    "line1\nline2\n"
      use Data::JavaScript; my @array = ( 1, 2, "f\no\no\n\bar" ); print $_,$/ for jsdump( my_array => \@array); __DATA__ var my_array = new Array; my_array[0] = 1; my_array[1] = 2; my_array[2] = 'f\012o\012o\012\010ar';
      This confirms it for me
      <a href="javascript:alert('f\012o\012o\012\010ar');"> alert('f\012o\012o\012\010ar') </a>

      MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
      I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
      ** The third rule of perl club is a statement of fact: pod is sexy.

        In that case,
        my $string = ... from db ...; my $jscode = $string; $jscode =~ s/(\W)/ sprintf('\\0%o', ord($1)) /ge; $jscode = qq{"$jscode"};
        would also work.