JavaScript String Methods

String methods allow you to manipulate text, extract substrings, change case, and perform searches. Mastering these methods makes working with textual data more efficient and flexible.

Key Topics

Changing Case

Use toUpperCase() and toLowerCase() to change the case of strings.

let text = "Hello World";
console.log(text.toUpperCase());
console.log(text.toLowerCase());

Output

> HELLO WORLD

> hello world

Explanation: The string "Hello World" is converted to uppercase and then lowercase using the respective methods.

Substring Extraction

Methods like slice(), substring(), and substr() allow you to extract parts of a string.

let phrase = "JavaScript";
console.log(phrase.slice(0,4)); // "Java"
console.log(phrase.substring(4,10)); // "Script"

Output

> Java

> Script

Explanation: The slice() method extracts "Java" from the start, and substring() retrieves "Script" from the remaining part of the string.

Trimming Whitespace

The trim() method removes whitespace from both ends of a string, ensuring cleaner input and output.

let userInput = "   Hello!   ";
console.log("Before Trim:", userInput);
console.log("After Trim:", userInput.trim());

Output

> Before Trim: Hello!

> After Trim: Hello!

Explanation: The trim() method removes the leading and trailing spaces, leaving a clean "Hello!" string.

JavaScript Usage in DOM

This DOM-based example demonstrates using string methods to format and display user input on a webpage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>String Methods in DOM</title>
</head>
<body>
    <h1>String Methods Demo</h1>
    <button onclick="formatText()">Format Text</button>
    <p id="output"></p>

    <script>
        function formatText() {
            let raw = "   JavaScript Methods   ";
            let formatted = raw.trim().toUpperCase();
            document.getElementById("output").textContent = formatted;
        }
    </script>
</body>
</html>

Key Takeaways

  • Changing Case: toUpperCase() and toLowerCase() modify string casing.
  • Substrings: slice(), substring(), and substr() extract parts of a string.
  • Trimming: trim() removes extra spaces.
  • DOM Integration: Apply string methods to clean and format displayed text.