We can get the length of a string using the .length
property like this:
let message = "Hello world";
// Printing the length:
console.log(message.length); // Output: 11
// Changing the message:
message += "!";
// Printing the new length:
console.log(message.length); // Output: 12
Accessing characters from the end:
The length is useful for accessing characters from the end of a string.
Because strings are 0-indexed, the index of the last character is length - 1:
let message = "Hello world";
let length = message.length;
// Printing the last character:
console.log(message[length - 1]); // Output: d
// Printing the second to last character:
console.log(message[length - 2]); // Output: l
In general, if you want the nth last character, you access message[length - n]
.
Slicing characters from the end:
The length is also useful for slicing some characters from the end of a string:
let message = "Hello world";
let length = message.length;
// Slicing last 4 characters:
let lastChars = message.slice(length - 4);
console.log(lastChars); // Output: orld
// Slicing last 7 characters:
lastChars = message.slice(length - 7);
console.log(lastChars); // Output: o world
In general, if you want the last n characters, you use message.slice(length - n)
.
Assignment
Follow the Coding Tutorial and let's practice with string length!
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore how to work with string lengths in JavaScript. Understanding how to manipulate and access string lengths is fundamental in programming, as strings are a core data type used in almost every application. Whether you are processing user input, generating dynamic content, or performing data validation, knowing how to handle string lengths efficiently is crucial.
The .length
property in JavaScript returns the number of characters in a string. This property is essential for various string operations, such as accessing specific characters, slicing parts of the string, and validating input lengths.
Here is a simple example to illustrate the concept:
let message = "Hello world";
console.log(message.length); // Output: 11
In this example, the string "Hello world" has 11 characters, including the space.
Let's delve deeper into some key concepts and techniques for working with string lengths:
Since strings are 0-indexed, the last character of a string is at the index length - 1
. This is useful for tasks such as reversing a string or checking the last character for specific conditions.
let message = "Hello world";
let length = message.length;
console.log(message[length - 1]); // Output: d
console.log(message[length - 2]); // Output: l
The slice()
method can be used to extract a portion of a string. By combining slice()
with the .length
property, you can easily slice characters from the end of a string.
let message = "Hello world";
let length = message.length;
let lastChars = message.slice(length - 4);
console.log(lastChars); // Output: orld
Let's look at some practical examples and use cases:
Suppose you are building a form where users need to enter a username. You can use the .length
property to ensure the username meets the required length criteria.
function validateUsername(username) {
if (username.length < 5) {
return "Username must be at least 5 characters long.";
}
return "Username is valid.";
}
console.log(validateUsername("John")); // Output: Username must be at least 5 characters long.
console.log(validateUsername("Johnny")); // Output: Username is valid.
When displaying text in a limited space, you might need to truncate the string and add an ellipsis. The .length
property helps determine where to cut off the string.
function truncateString(str, maxLength) {
if (str.length > maxLength) {
return str.slice(0, maxLength) + "...";
}
return str;
}
console.log(truncateString("Hello world", 5)); // Output: Hello...
console.log(truncateString("Hello", 10)); // Output: Hello
Here are some common mistakes to avoid and best practices to follow:
length - 1
.Let's explore some advanced techniques for working with string lengths:
Reversing a string involves accessing characters from the end and constructing a new string. This can be achieved using a loop and the .length
property.
function reverseString(str) {
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseString("Hello world")); // Output: dlrow olleH
A palindrome is a string that reads the same backward as forward. You can use the .length
property to compare characters from both ends.
function isPalindrome(str) {
let length = str.length;
for (let i = 0; i < length / 2; i++) {
if (str[i] !== str[length - 1 - i]) {
return false;
}
}
return true;
}
console.log(isPalindrome("racecar")); // Output: true
console.log(isPalindrome("hello")); // Output: false
Here is a well-commented code snippet demonstrating the correct use of string length:
let message = "Hello world";
// Print the length of the string
console.log(message.length); // Output: 11
// Access the last character
console.log(message[message.length - 1]); // Output: d
// Slice the last 4 characters
let lastChars = message.slice(message.length - 4);
console.log(lastChars); // Output: orld
// Validate input length
function validateInput(input) {
if (input.length < 5) {
return "Input is too short.";
}
return "Input is valid.";
}
console.log(validateInput("Hi")); // Output: Input is too short.
console.log(validateInput("Hello")); // Output: Input is valid.
Debugging and testing are crucial for ensuring your code works as expected. Here are some tips:
Example test case:
function testValidateInput() {
console.assert(validateInput("Hi") === "Input is too short.", "Test Case 1 Failed");
console.assert(validateInput("Hello") === "Input is valid.", "Test Case 2 Failed");
console.assert(validateInput("JavaScript") === "Input is valid.", "Test Case 3 Failed");
}
testValidateInput();
Here are some strategies for approaching problems related to string lengths:
In this lesson, we covered the basics of working with string lengths in JavaScript. We explored how to access and slice characters from the end of a string, validated input lengths, and discussed common pitfalls and best practices. By mastering these concepts, you can handle strings more effectively in your programming projects.
Remember to practice regularly and explore further applications to deepen your understanding.
Here are some additional resources to help you further your knowledge: