user2898990
user2898990

Reputation: 3

How to alert a string of entered text into separate line's?

I don't know how to alert a string of text that i input. I tried a few things but i feel i'm just guessing. This is my code without the case "list" added. Basically what i want to happen is to be able to input "list eggs bacon sausage" and for it too output(in seperate lines):

eggs bacon sausage

I'm not asking for anyone to do it but to help me try to understand how to do it.

I'm sorry for not explaining in great detail i don't have much time to finish so any feedback would be much appreciated.

<html>
<head>  
<body>

<script type="text/javascript">
   //begin function
   function Process() {
        //declare the variables
        var str = ("print" , "datetime" , "list" , "math");
        str = prompt("Input Text")
        var list = str.split(" ");
        //begin switch
        switch (list[0]) {
            //begin case
            case "print":
                alert(str.substring(6))
                //end case
                break;

            //begin case
            case "datetime":
                alert(Datetime())
            //end case
                break;

            default:
            alert("you type, "+str)
        }
        //end switch
    }
    //end function

    //begin function 
    function Datetime() {
        var currentdate = new Date();
        var datetime = "Date and Time today: " + 
                            currentdate.getDate() + "/" + 
                            (currentdate.getMonth() + 1) + "/" + 
                            currentdate.getFullYear() + " @ " + 
                            currentdate.getHours() + ":" + 
                            currentdate.getMinutes() + ":" + 
                            currentdate.getSeconds();

        return(datetime)
    }
    //end function
</script> 

<script type="text/javascript">

// do the process
    Process();
    Datetime()

</script>
</body>
</head>
</html>

Upvotes: 0

Views: 69

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107536

To add a "new line" to your strings, just concatenate a \n:

var test = "I'm on one line\n" + 
    "and I'm on another";

alert(test);

If you split your input by spaces into an array, you can put the array back together, with newlines, with join():

var str = myArray.join('\n');
alert(str);

To remove the first item from your array before you do that, use splice() shift():

myArray.shift();
var str = myArray.join('\n');

Upvotes: 2

Nick Germi
Nick Germi

Reputation: 403

Well your code works and gives the expected result, though you are missing a ; (Datetime();)

Live example: http://jsfiddle.net/ez666/8KAt6/2/

As for line breaks, you can use: alert("You typed: " + str.split(' ').join('\n'));

Upvotes: 0

Related Questions