How can i pass a string with multiple line to a javascript function ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mohan lal
    New Member
    • Mar 2011
    • 25

    How can i pass a string with multiple line to a javascript function ?

    Hi,

    I have a variable in php
    Code:
    $test = "This is a string
    It has multiple lines
    there are three total" ;
    (Output from a text area)

    I want to pass this variable to a javascript function

    I have write this in my php file
    Code:
    <?php echo "<script language=javascript>convert('$test');</script>"; ?>
    but this makes an error "Unterminat ed string literal" How can i solve this issue ??
    Last edited by Atli; May 4 '11, 05:36 AM. Reason: Please use [code] tags when posting code.
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    Unlike PHP, Javascript does not allow strings that span multiple lines.

    To do that in Javascript, you need to either do this:
    [code=javascript]
    var str = "First line \n\
    Second line \n\
    Third line";
    [/code]

    Or just:
    [code=javascript]
    var str = "First line\n" +
    "Second line\n" +
    "Third line";
    [/code]

    To get PHP to generate this, I suggest you look at the str_replace function. The idea would be to replace new lines (\n) with a new-line followed by a back-slash (\n\).

    Comment

    Working...