DEV Community

Cover image for Beginner JavaScript Project: How to reverse a sentence and display it on screen
Jessica Wilkins
Jessica Wilkins

Posted on

Beginner JavaScript Project: How to reverse a sentence and display it on screen

The best way to practice your JavaScript skills is to build small projects. In this article we will build a small app that takes in a sentence and reverses it.

We will be building out this project in CodePen. CodePen is a popular online code editor used by many developers around the world. It is free to use and you will need to create an account first and then fork the pen to get started. Here is the CodePen starter code you will need to fork that has all of the HTML and CSS.

Prerequisites
All of the HTML and CSS has been provided for you and we will not be covering any of that in this tutorial. This tutorial assumes that you have basic working knowledge of HTML and CSS. If you are interested in learning about HTML and CSS, then I suggest you go through freeCodeCamp's Responsive Web Design Course.

Table of contents

The basic functionality behind the reverse a sentence project

When you open up the CodePen starter code, you should see this result.

starter page

We want to build an app where a user inputs a sentence and clicks on the "Reverse Sentence" button, and the reversed sentence is displayed on the screen.

inputting sentence
reversed result

If the user clicks on the "Reverse Sentence" button without providing an input, then an alert with display asking them to provide a sentence.

alert message

Topics covered

Here is the complete list of topics covered in this project. You can click on any of the topics and it will take you to an article or MDN link to learn more.

Accessing HTML elements using JavaScript

Our application has three main HTML elements that we need access to in our JavaScript file. We need access to the input which contains the value for the user's sentence. We need access to the button which will be used to display the result when clicked on. And we also need access to the empty paragraph element which will display the result.

There are a few ways to access elements using JavaScript. In this project we are going to use the getElementById method. This method will access the HTML element that matches the id that we specify. Since id names have to be unique in an HTML document, we can be certain that we are getting back the correct element.

Here is the basic syntax for the getElementById method:

document.getElementById(id);
Enter fullscreen mode Exit fullscreen mode

Let's first start by accessing the input which has an id of user-sentence.

document.getElementById("user-sentence");
Enter fullscreen mode Exit fullscreen mode

We want to be able to assign that to a variable so we can use it later on in our program. We are going to create a const variable called userSentence and assign it the document.getElementById("user-sentence"). We are using the const keyword here because this const variable will not be re assigned.

const userSentence = document.getElementById("user-sentence");
Enter fullscreen mode Exit fullscreen mode

If you are curious on what this document.getElementById("user-sentence") returns, then I would suggest using console.log like this:

const userSentence = document.getElementById("user-sentence");
console.log(userSentence);
Enter fullscreen mode Exit fullscreen mode

Note: To access the console in CodePen, click on the console button in the bottom left hand corner of the screen

CodePen console

You can use console.log to print messages to the console output. This method comes in handy when you need to understand what your code is doing.

Now that we understand how to use console.log, we can remove that line from our program.

The next steps would be to access the paragraph element with the id of reversed-str-result. We can use the getElementById method again and assign it to a variable called reversedStrElement.

const reversedStrElement = document.getElementById("reversed-str-result");
Enter fullscreen mode Exit fullscreen mode

The last element we need access to would be the button with the id of reverse-str-btn. We can use the getElementById method again and assign it to a variable called reversedStrBtn.

const reversedStrBtn = document.getElementById("reverse-str-btn");
Enter fullscreen mode Exit fullscreen mode

Your first three lines of code inside the JavaScript section should look like this:

const userSentence = document.getElementById("user-sentence");
const reversedStrElement = document.getElementById("reversed-str-result");
const reversedStrBtn = document.getElementById("reverse-str-btn");
Enter fullscreen mode Exit fullscreen mode

Creating the reverse sentence button functionality

When the user clicks on the "Reverse Sentence" button, we want to display the reversed sentence on the screen. We need to start by using the addEventListener method.

Adding an event listener to the Reverse Sentence button

The addEventListener is used to detect events in your program and execute a function when that event has occurred. The event that we are listening for is the click event to represent when a user clicks on a button.

Below the const variables, let's add an event listener to our reversedStrBtn.

reversedStrBtn.addEventListener("click", () => {
  // the rest of our functionality will go here
});
Enter fullscreen mode Exit fullscreen mode

We can test this out by adding a console.log that will print the message "This button was clicked".

reversedStrBtn.addEventListener("click", () => {
  console.log("This button was clicked");
});
Enter fullscreen mode Exit fullscreen mode

Open up your console and click on the button. You should see the following result:

logging button message

Now that we know our button is working, we can go ahead and remove that console.log.

reversedStrBtn.addEventListener("click", () => {
  // the rest of our functionality will go here
});
Enter fullscreen mode Exit fullscreen mode

Accessing the value from the input element

We need to be able to get the user's input so we can successfully reverse it and display it on the screen. We can accomplish this by adding .value to our userSentence variable.

Inside the function for our event listener, let's add a console.log for userSentence.value.

reversedStrBtn.addEventListener("click", () => {
  console.log(userSentence.value);
});
Enter fullscreen mode Exit fullscreen mode

Open up your console, type in a sentence and click on the "Reverse Sentence" button to see the value in the console.

logging out input value

We can remove that console.log and assign that user value to a const variable called userValue.

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
});
Enter fullscreen mode Exit fullscreen mode

Adding an alert for users that do not provide an input

Before we can start reversing a string, we need to check if the user provides a value.

Below the userValue variable, we need to add an if statement. An if statement is a type of conditional statement that will run a block of code if the condition is true.

Here is the basic syntax for an if statement:


if(/*condition is true*/){
    // run this code here
}
Enter fullscreen mode Exit fullscreen mode

For our condition, we want to check if the user value is an empty string. Empty strings in JavaScript are considered falsey values. In if statements, falsey values are coerced to false. We want to use the ! operator which reverses the boolean value (ex. true is now false, and false is now true).

This is what our if will look like:

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;

  if (!userValue) {
    // run this code here if condition is true
  }
});
Enter fullscreen mode Exit fullscreen mode

The !userValue is basically saying run this code in the if statement if userValue is not false. If you don't feel comfortable with the ! operator, then you could rewrite your if statement like this:

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (userValue === "") {
    // run this code here if condition is true
  }
});
Enter fullscreen mode Exit fullscreen mode

Inside the if statement, we want to add an alert to let users know that they need to provide a sentence. Below that alert, we need to add the return statement because we want to exit our function if the user does not provide an input.

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
});
Enter fullscreen mode Exit fullscreen mode

Click on the "Reverse Sentence" button without providing an input to see the alert.

reverse sentence alert

Reversing the sentence using the split, reverse, and join methods

There are many different ways to reverse a string. In this project we are going to use three built in JavaScript methods.

The first step is to take our userValue and split that into individual characters. We can use the split method which takes in a string and creates an array of characters.

Add a console.log below our if statement for the split method.

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  console.log(userValue.split(""));
});
Enter fullscreen mode Exit fullscreen mode

Open up the console, provide an input and click on the "Reverse Sentence" button to see the console results.

split method demo

Next, we want to take that array of characters and reverse it using the reverse method.
Note: I am using a method called chaining here which is used to chain multiple methods together

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  console.log(userValue.split("").reverse());
});
Enter fullscreen mode Exit fullscreen mode

Open up the console, provide an input and click on the "Reverse Sentence" button to see the console results.

reverse method demo

Lastly, we need to convert that array of characters back into a string. We can use the join method to accomplish this.

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  console.log(userValue.split("").reverse().join(""));
});
Enter fullscreen mode Exit fullscreen mode

Open up the console, provide an input and click on the "Reverse Sentence" button to see the console results.

using the join method

We can remove the console.log and assign the reversed sentence to a const variable called reversedSentence.

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  const reversedSentence = userValue.split("").reverse().join("");
});
Enter fullscreen mode Exit fullscreen mode

Displaying the reversed sentence and working with template strings

Now that we have the reversed sentence, we want to be able to display that result on the screen. We can use what are called template strings(or template literals) to inject variables inside strings. Template strings use backticks instead of double("") or single quotes('').

Here is what our template string will look like:

`Reversed sentence: ${reversedSentence}`;
Enter fullscreen mode Exit fullscreen mode

We want that value to display in the reversedStrElement which represents the empty paragraph element in our HTML document. We can use the innerText method to render the reversed sentence on the page.

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  const reversedSentence = userValue.split("").reverse().join("");
  reversedStrElement.innerText = `Reversed sentence: ${reversedSentence}`;
});
Enter fullscreen mode Exit fullscreen mode

Resetting the input value after the result is displayed on the page

When the result is displayed on the page, it would be nice if the input value would clear out. We accomplish this by assigning an empty string to the userSentence.value.

reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }

  const reversedSentence = userValue.split("").reverse().join("");
  reversedStrElement.innerText = `Reversed sentence: ${reversedSentence}`;
  userSentence.value = "";
});
Enter fullscreen mode Exit fullscreen mode

Now you can test out your project with a variety of sentences and should see the reversed results.

Here is the entire code for our project. Here is the final working result.

Conclusion

I hope you learned a lot with this beginner JavaScript project. For more JavaScript projects like these, please check out the following article:

Latest comments (9)

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

You need no tool...

use intl.segmenter

Collapse
 
codergirl1991 profile image
Jessica Wilkins

Thank you for sharing

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited
"H❤️ell🙌🙌o")
Enter fullscreen mode Exit fullscreen mode

returns

o�🙌�lle️❤H
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codergirl1991 profile image
Jessica Wilkins

There is a good tool that handles those edge cases for the split method. Esrever is a package that will reverse any string of Unicode symbols.
github.com/mathiasbynens/esrever
You can check out their demo here
mothereff.in/reverse-string

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You can cover a lot of the cases by just doing:

[...userValue].reverse().join("")

// with "H❤️ell🙌🙌o", this gives us "o🙌🙌lle️❤H" - much closer
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
codergirl1991 profile image
Jessica Wilkins

Yeah, that's true.

There still might be special unicodes that this method doesn't cover too. But the goal of this article was to show just one way to reverse a string. Just a small beginner project to get people started. ☺

Thread Thread
 
frankwisniewski profile image
Frank Wisniewski

If you want to show something, you have to show it properly.

Thread Thread
 
frankwisniewski profile image
Frank Wisniewski • Edited

@jonrandy
That's a solution that doesn't always work. Use intl.segmenter

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

I know it doesn't always work. I stated that