Start learning free

LESSON 64 OF 410 · STRINGS I

String Length in JavaScript

Lesson Read the full explanation

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.


STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · STRINGS I

    String Length in JavaScript, explained

    Introduction

    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.

    Understanding the Basics

    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.

    Main Concepts

    Let's delve deeper into some key concepts and techniques for working with string lengths:

    Accessing Characters from the End

    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
    

    Slicing Characters from the End

    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
    

    Examples and Use Cases

    Let's look at some practical examples and use cases:

    Example 1: Validating Input Length

    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.
    

    Example 2: Truncating Strings

    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
    

    Common Pitfalls and Best Practices

    Here are some common mistakes to avoid and best practices to follow:

    • Off-by-One Errors: Remember that string indices are 0-based, so the last character is at length - 1.
    • Immutable Strings: Strings in JavaScript are immutable, meaning you cannot change a character directly. Instead, create a new string with the desired modifications.
    • Use Template Literals: For better readability and maintainability, use template literals (backticks) when constructing strings with dynamic content.

    Advanced Techniques

    Let's explore some advanced techniques for working with string lengths:

    Reversing a String

    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
    

    Palindrome Check

    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
    

    Code Implementation

    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

    Debugging and testing are crucial for ensuring your code works as expected. Here are some tips:

    • Use Console Logs: Print intermediate values to the console to understand the flow of your code.
    • Write Test Cases: Create test cases to validate your functions. Use tools like Jest or Mocha for automated testing.

    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();
    

    Thinking and Problem-Solving Tips

    Here are some strategies for approaching problems related to string lengths:

    • Break Down the Problem: Divide the problem into smaller, manageable parts. Focus on one part at a time.
    • Use Pseudocode: Write pseudocode to outline your logic before implementing it in JavaScript.
    • Practice Regularly: Solve coding exercises and projects to reinforce your understanding and improve your skills.

    Conclusion

    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.

    Additional Resources

    Here are some additional resources to help you further your knowledge:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free