CloudRookie
CloudRookie

Reputation: 29

Convert to lowercase, uppercase, and then split the string into its own lines

I am trying to get a better hang of doing this and have been playing around with strings. What I am trying to do is collect a user input as a string and manipulate it so that when I display the text, whatever they wrote would be first displayed in all lower case, then all uppercase, then all of the text divided into its own line.

So, the output would be like this if I enter: This is an example

this is an example

THIS IS AN EXAMPLE

This

is

an

example

I feel like this is supposed to be a lot easier than it looks, but I am trying to do an all lowercase so far, but cannot get that to work so far (as well as the other two parts). I think that if I get the lowercase right, I just repeat the same thing for uppercase and splitting it.

    <button onclick="myFunction()">Try it</button>

<p id="test"></p>

<script>
function myFunction() {
    var person = prompt("Please enter a phrase");
    if (person != null) {
        document.getElementById("test").innerHTML =
        test.toLowerCase;
        document.getElementById("test").innerHTML =
        test.toUpperCase;
        document.getElementById("test").innerHTML =
        test.split("\n");
    }
}
</script>

The above is what I am playing with so far, I get undefined when I click the button to test it. Can someone help me edit this?

Upvotes: 0

Views: 4061

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

  1. functions are invoked using ()
  2. your variable is person not test
  3. you want to split on space not \n
  4. you want to ADD to test innerHTML, not replace it each time
  5. to get line breaks in HTML, use <br> tag

I've gone for code that assigns innerHTML once, as this is more performant than adding to it a bit at a time - of course, with such a simple example there's no perceived difference, however I thought I should mention why I chose to use this odd methodology

function myFunction() {
    var person = prompt("Please enter a phrase");
    if (person != null) {
        document.getElementById("test").innerHTML = [
          person.toLowerCase(),
          person.toUpperCase(),
          person.split(" ").join('<br>')
        ].join("<br>");
    }
}
<button onclick="myFunction()">Try it</button>
<p id="test"></p>

Upvotes: 3

Ryan Yuan
Ryan Yuan

Reputation: 2566

You may want to split the string into words first and use join() function with <br /> tags to render them into multiple lines of words.

function myFunction() {
    var person = prompt("Please enter a phrase");
        if (person != null) {
            document.getElementById("test").innerHTML +=
        person.toLowerCase() + "<br />";
        document.getElementById("test").innerHTML +=
        person.toUpperCase() + "<br />";
        document.getElementById("test").innerHTML +=
        person.split(' ').join('<br />');
    }
}

Upvotes: 2

Related Questions