简体   繁体   中英

How to give multiple lines as input to a javascript variable

I wanted to fill a text area with some text as the user presses a button. But I have a problem that the variable to fill the text takes only single line input but I wanted to have some text with multiple lines and indentations

<!DOCTYPE html>
<html>
    <head>
        <title>SampleCodes</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <script type="text/javascript">
            function fill(){
                var text1 ="#include<stdio.h>
                            #include<conio.h>
                            void main()
                           {
                             printf("Hello World");
                           }"
              document.forms.myform.area.value=text1;
            }
        </script>
        <div>
            <button onclick="fill()">Program 1</button>
            <button>Program 2</button>
            <button>Program 3 </button>
            <button>Program 4</button>
        </div>
        <div class="wrapper">
            <div class="gfg">
                <form name="myform">
                    <textarea name="area" rows="30" cols="60">
                    </textarea>
                </form>
            </div>
        </div>
    </body>
</html>

You can simply use Template string ``

var text1 =`#include<stdio.h>
            #include<conio.h>
            void main()
              {
                printf("Hello World");
              }`

In ES5 multiline text can be escaped with a backslash character ( \\ ).

var text1 = "#include<stdio.h> \
             #include<conio.h> \
             void main() \
             { \
                 printf(\"Hello World\"); \
             }";

If you are using ES6 you can use backticks to wrap multiline strings.

var text1 = `#include<stdio.h>
             #include<conio.h>
             void main()
             {
                 printf("Hello World");
             }`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM