String Manipulation
Strings are one of the key primitive data types in JavaScript. We’ve seen in prior tutorials how we can convert between numbers and text. Those aren’t the only ways we might need to manipulate textual data. In this tutorial, we’ll explore some very helpful functions built into JavaScript’s string data type.
Learning Outcome Guide
At the end of this tutorial, you should be able to:
- Determine the number of characters in a string
- Identify potential use cases of the following string functions
.trim()(and variants).toUpperCase()and.toLowerCase().padStart()and.padEnd().replaceAll()
Cleaning Text
Section titled “Cleaning Text”Where does information come from? We’ve been putting information directly into our code as hard-coded values (and will do so for a while yet), but as soon as we’re able to get data entered into our program from outside (e.g.: from the user) we might want to examine or “clean” it up. When we don’t know what text to expect, we might want to examine it or transform it some way.
-
Launch VS Code side-by-side with an external terminal. (See the first tutorial in this QuickStart series if you need a refresher on how to do this.)
-
Create a file called
controlling-text.jsin the same folder as the scripts from the earlier tutorials. Run it in the terminal using Node.controlling-text.js console.log('Exploring strings in JavaScript');console.log('===============================');console.log();Terminal window node --watch controlling-text.js -
Let’s begin with a function that will display the contents of some textual value along with the length of the string. Every string has a property called
.lengththat tells us how many characters are in the string.controlling-text.js function logText(text) {console.log(`The text '${text}' is ${text.length} characters long.`);} -
Let’s call our function with some test data. Notice how our clever use of literal single-quotes in
logText()helps us to actually see where the string’s characters start and end.controlling-text.js logText('This is a test');logText(''); // An empty stringYou will see the following output.
Terminal window Exploring strings in JavaScript===============================The text 'This is a text' is 14 characters long.The text '' is 0 characters long. -
If we had some text entering our program from the outside (say, from something entered by the end-user of our program), we might be interested in “cleaning up” the input by removing any whitespace surrounding the text. There are three string functions that allow us to do just that:
.trimStart(),.trimEnd(), and.trim(). Let’s explore those functions.controlling-text.js // At some point, a string may have leading or trailing whitespacelet input = ' User Input ';logText(input);logText(input.trimStart());logText(input.trimEnd());logText(input.trim());Again, our clever use of quotes in the
logText()function helps us notice any leading or trailing spaces.Terminal window The text ' User Input ' is 15 characters long.The text 'User Input ' is 12 characters long.The text ' User Input' is 13 characters long.The text 'User Input' is 10 characters long. -
Here’s something important. All of the string functions we’re exploring in this tutorial will produce a new string value without changing the original variable’s value. Look back at the trimming we did for the
inputvariable. Each time we trimmed the variable, it produced a separate value that was sent intologText(). Theinputvariable still has its leading and trailling whitespace.controlling-text.js // Let's output it one more timelogText(input); -
These trim methods work with more than just spaces. They will remove tabs (
'\t') and newline ('\n') characters as well.controlling-text.js input = '\n\tEscape Characters\t\t';logText(input);logText(input.trim());logText('\t'); // Tab characterlogText('\n'); // Newline characterIn the terminal, we should see the following.
Terminal window The text 'Escape Characters ' is 21 characters long.The text 'Escape Characters' is 17 characters long. -
How many characters do you think are in the string
'\n\tEscape Characters\t\t'? Visually, in the console, tabs appear several characters long. In reality, they are only regarded as a single character.controlling-text.js logText('\t'); // Tab characterlogText('\n'); // Newline characterFocusing on the escape characters by themselves, we more readily see that their length are one character each.
Terminal window The text '' is 1 characters long.
While we can’t control the exact text coming into our program from the user, we can do some simple clean up by removing leading and trailing whitespace from the strings. Trust me, that will become very helpful at some point in your programming career.
Formatting Text
Section titled “Formatting Text”There are other ways we can modify our strings. This can be helpful in several ways. One of the more obvious uses is to control formatting of our output.
Likewise, there’s a function to change it to lower-case (.toLowerCase()). We can
-
We’re starting a new section in our script file. Let’s add a blank line of output along with a heading. To make our heading stand out, we’ll transform the text to all upper-case characters (
.toUpperCase()). Add the following lines to your script file.controlling-text.js console.log(); // a blank linelet heading = 'Manipulating Text';console.log(heading.toUpperCase());You should see the heading appear in all upper-case letters.
Terminal window MANIPULATING TEXT -
Imagine that we also wanted to provide some dashes as an “underline” to the heading text we just displayed in the console. There is a function called
padEnd()that we can use. Let’s use it with a humble empty string.controlling-text.js let underline = ''.padEnd(heading.length, '-');console.log(underline);This function does two things:
- It ensures that the resulting string is a minimum length. In this case, we want the length to match that of our heading.
- It pads or “fills” the remaining length with a specific character. We chose a dash to underline our heading.
Terminal window MANIPULATING TEXT-----------------Reflect on the fact that we started with an empty string. The reason we did this was to ensure the entire length of our underline matched that of our heading.
-
Adding extra characters to a string to ensure a minimum length can be helpful in other formating scenarios. Imagine that we wanted to produce a tabular output such as the following.
Terminal window |-----------------|------------|| Regular Dice | $ 4.32 || Trick Dice | $ 4.78 ||=================|============|| Total | $ 9.10 ||-----------------|------------|Through the use of
.padEnd()and.padStart()we can ensure the data in our columns will always meet a certain length. -
Add the following function to your script. We want the text in the first column to be 15 characters wide, while the second column’s amount should be eight characters of space. We’ll call this function every time we have a row of data to show in our table.
controlling-text.js console.log(); // a blank linefunction logLineItem(description, amount) {let colA = description.padEnd(15);let colB = amount.padStart(8);console.log(`| ${colA} | $ ${colB} |`);}Something’s different about our use of
.padEnd()(and.padStart()) from our earlier example. This time, we haven’t provided a character to use for filling in the additional space. When that argument is omitted, these functions will use a single space (' ') as a default padding character.Before we move on, take another look at the template string. There’s some extra characters that increase each columns’ width, and we’ll address that in our next steps.
-
Now, let’s create some variables to build a border. Accounting for the additional hard-coded characters of our template string, the overall width of our columns will be 17 and 12 characters respectively.
controlling-text.js let blank = '';let colABorder = blank.padStart(17, '-');let colBBorder = blank.padStart(12, '-');let border = `|${colABorder}|${colBBorder}|`; -
We’re almost ready to display our table. First, we need some values to work with. It’s time to bring in what we learned about Math in JavaScript.
controlling-text.js let regularDice = 4.32;let trickDice = 4.78;let total = regularDice + trickDice; -
Now we can display our table. Let’s start with the top border and our two line items for the dice we’re purchasing.
controlling-text.js console.log(border);logLineItem('Regular Dice', regularDice.toFixed(2));logLineItem('Trick Dice', trickDice.toFixed(2)); -
For the middle border, we’ll swap out the dashes and put in equal signs. To do that, we’ll leverage another helpful function:
.replaceAll()controlling-text.js console.log(border.replaceAll('-', '='));The
.replaceAll()function takes two arguments. The first is the existing string we want removed. The second is the string we want to put in its place. -
Time to display the total and the bottom border.
controlling-text.js logLineItem('Total', total.toFixed(2));console.log(border);If all has gone well, we should see our tabular output
Terminal window |-----------------|------------|| Regular Dice | $ 4.32 || Trick Dice | $ 4.78 ||=================|============|| Total | $ 9.10 ||-----------------|------------| -
To wrap up, let’s add in a final bit of code for our script. See if you can predict what output this will produce.
controlling-text.js let ending = 'The End';let length = ending.length;// Reformatconsole.log(ending.toLowerCase().padStart(length + 4, '\n-- ').padEnd(length + 7, ' --'));That last line is rather complex (and we wouldn’t want to do that in real life). But my goal is to challenge you to think carefully about the order of operations in terms of function calls.
Conclusion
Section titled “Conclusion”This tutorial completes our look at the two foundational types of data - strings and numbers. Along the way, we examined several string functions that can prove helpful in the future.
Our next tutorial will introduce complex data types in JavaScript.
Self-Check
Section titled “Self-Check”Check your understanding of the learning outcomes below. Treat each code sample as a separate program. Choose an answer to see an explanation; when a question asks for multiple answers, select all that apply.
Quiz answers on this page are saved to your browser's local storage and persist between visits.
Which expression gives the number of characters in the plain-text string 'Hello'?
-
'Hello'.length() -
'Hello'.length -
'Hello'.size
length is a property, so it does not take parentheses. For this string, its value is 5.
What is the value of text.length?
let text = '\tHi\n';-
4 -
6 - It depends on how wide the terminal displays a tab.
The tab and newline each count as one character here, alongside H and i. Their screen appearance does not change this string’s length.
You want to remove whitespace from both ends of a name while keeping the space between the words. Which call should you use?
let name = ' Ada Lovelace ';-
name.replaceAll(' ', '') -
name.trimStart() -
name.trim()
.trim() removes leading and trailing whitespace, including spaces, tabs, and newlines. It leaves the space inside 'Ada Lovelace' intact.
Which statements about trimming are correct? Select all that apply.
-
.trimStart()removes whitespace only from the beginning. -
.trimEnd()removes whitespace only from the end. -
.trim()removes every space inside the string. - Calling
.trim()automatically replaces the value in the original variable.
The trim methods return new strings. To retain a trimmed value in the same variable, assign the result, as in input = input.trim().
Which pair of expressions produces 'REPORT' and 'report', respectively, from let title = 'Report';?
-
title.toUpperCase()andtitle.toLowerCase() -
title.toLowerCase()andtitle.toUpperCase() -
title.trimStart()andtitle.trimEnd()
Case conversion is useful for formatting headings or normalizing text before comparison. These methods return new strings without changing title.
Which expression pads the text '42' with zeros to produce '00042'?
-
'42'.padEnd(5, '0') -
'42'.padStart(3, '0') -
'42'.padStart(5, '0')
The first argument is the target total length, not the number of characters to add. padStart() adds padding before the original text.
You want a description left-aligned in a column at least 15 characters wide. Which expression fits that purpose?
-
description.padStart(15) -
description.padEnd(15) -
description.trimEnd(15)
padEnd(15) adds spaces after a shorter description. Padding defaults to spaces, and it does not truncate descriptions that are already longer than 15 characters.
What are the values of divider and updated after this code?
let divider = '---';let updated = divider.replaceAll('-', '=');- Both are
'==='. -
divideris'---'andupdatedis'==='. -
divideris'---'andupdatedis'=--'.
replaceAll() replaces every matching occurrence in the returned string. Like the other string methods in this tutorial, it leaves the original value unchanged.
Quiz Progress
0 / 0 questions answered (0%)
0 correct
Your score
0%
0 / 0 correct
Answered: 0 / 0 (0%)