Strings & Text Processing (Methods, Escaping & 5 Projects)

๐ŸŸจ JavaScript (ES2026+) ๐ŸŸข Lesson 9 ๐Ÿ“‚ Phase 06: Strings Mastery ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this lesson: Creating Strings ยท Quotes & Template Literals ยท length & charAt() ยท toUpperCase/toLowerCase ยท trim ยท includes/startsWith/endsWith ยท slice vs substring ยท replace/replaceAll ยท split ยท repeat ยท Escape Characters ยท 5 Projects

Welcome to Phase 6: Strings Mastery! In JavaScript, text is handled through Strings. Strings in JavaScript are immutable sequences of UTF-16 character code units. In this masterclass guide, you will learn how to create strings using single quotes, double quotes, and modern ES6 Template Literals, master over 15 built-in string manipulation methods, understand character indexing, escaping, slicing, string replacement, palindrome verification, and build 5 interactive text-processing mini-projects.

1Creating Strings (Single, Double Quotes & Template Literals)

JavaScript lo strings create cheyyadaniki 3 approaches unnaayi:

String DelimiterSyntaxKey Features
1. Single Quotes 'Hello World' Classic literal. Useful when string contains double quotes.
2. Double Quotes "Hello World" Classic literal. Useful when string contains apostrophes.
3. Template Literals (ES6 โญ) `Hello ${name}` Supports String Interpolation (`${expression}`), multi-line strings, and embedded JavaScript code without concatenation.
JavaScript โ€” Quotes & Template Literals โ–ถ Run Code
"use strict";

const language = "JavaScript";

console.log(language.length);
console.log(language.toUpperCase());
console.log(language.includes("Script"));
console.log(`I am learning ${language}`);
2String Length, Indexing & charAt()

Strings are zero-indexed (first character index is 0):

  • str.length โ€” Total number of characters (property, not a method).
  • str[0] โ€” Bracket notation to read character at index 0.
  • str.charAt(0) โ€” Method to read character at index 0 (returns empty string "" if out of bounds, unlike undefined).
  • str.at(-1) โ€” Modern ES2022 method supporting negative indices (last character).
3Essential String Methods Master Table
MethodDescriptionExampleResult
toUpperCase()Converts string to uppercase."js".toUpperCase()"JS"
toLowerCase()Converts string to lowercase."JS".toLowerCase()"js"
trim()Removes whitespace from both ends." hi ".trim()"hi"
includes(sub)Checks if substring exists (boolean)."JavaScript".includes("Script")true
startsWith(sub)Checks if string starts with substring."Hello".startsWith("He")true
endsWith(sub)Checks if string ends with substring."image.png".endsWith(".png")true
indexOf(sub)Returns first index of match (or -1)."developer".indexOf("el")3
split(delim)Splits string into array of strings."a,b,c".split(",")["a", "b", "c"]
repeat(count)Repeats string N times."โญ".repeat(3)"โญโญโญ"
4Extracting Text: slice() vs substring()
Featureslice(start, end) โญ Recommendedsubstring(start, end)
Negative Indicesโœ… Counts backward from end: "Hello".slice(-2) // "lo"โŒ Treats negative index as 0
start > endReturns empty string ""Swaps indices automatically
JavaScript โ€” slice vs substring โ–ถ Run Code
"use strict";

const message = "JavaScript Masterclass 2026";

console.log("slice(0, 10):", message.slice(0, 10));     // "JavaScript"
console.log("slice(-4):", message.slice(-4));           // "2026"
console.log("substring(0, 10):", message.substring(0, 10)); // "JavaScript"
5Replacing Text: replace() vs replaceAll()
  • str.replace("old", "new") โ€” Replaces ONLY the first match.
  • str.replaceAll("old", "new") โ€” Replaces ALL occurrences in the entire string (ES2021).
JavaScript โ€” replace vs replaceAll โ–ถ Run Code
"use strict";

const sentence = "Java is great, Java is fast, Java is everywhere!";

console.log("replace():", sentence.replace("Java", "JavaScript"));
// Only first "Java" changed!

console.log("replaceAll():", sentence.replaceAll("Java", "JavaScript"));
// All 3 "Java" occurrences replaced with "JavaScript"!
6Escape Characters & Palindrome Checking

Special characters ni strings lo embed cheyyadaniki backslash \ escape character vadathamu:

  • \n โ€” New Line
  • \t โ€” Tab Indent
  • \' or \" โ€” Quotation marks inside literal
  • \\ โ€” Literal backslash character

Palindrome Algorithm

Oka word/sentence mundhu nunchi or venuka nunchi chadivina okela unte dheenini Palindrome antaru (e.g. "madam", "racecar"):

JavaScript โ€” Palindrome Checker โ–ถ Run Code
"use strict";

function isPalindrome(str) {
    // 1. Sanitize: lowercase and remove non-alphanumeric chars
    const cleaned = str.toLowerCase().replaceAll(" ", "");
    
    // 2. Reverse string using split-reverse-join
    const reversed = cleaned.split("").reverse().join("");
    
    // 3. Compare
    return cleaned === reversed;
}

console.log("is 'racecar' Palindrome?", isPalindrome("racecar")); // true
console.log("is 'madam' Palindrome?", isPalindrome("madam"));     // true
console.log("is 'javascript' Palindrome?", isPalindrome("javascript")); // false
75 Text-Processing Mini Projects

Mastering string processing through 5 real-world applications:

Project 1: Word Counter

JavaScript โ€” Word Counter โ–ถ Run Code
"use strict";

function countWords(text) {
    if (!text.trim()) return 0;
    // Split by one or more whitespace characters
    const words = text.trim().split(/\s+/);
    return words.length;
}

const article = "JavaScript is a versatile language powering the modern web and cloud APIs.";
console.log("Total Words:", countWords(article)); // 12

Project 2: Character Counter & Analytics

JavaScript โ€” Character Counter โ–ถ Run Code
"use strict";

function analyzeText(text) {
    const totalChars = text.length;
    const withoutSpaces = text.replaceAll(" ", "").length;
    const spacesCount = totalChars - withoutSpaces;
    
    return {
        totalCharacters: totalChars,
        charactersWithoutSpaces: withoutSpaces,
        spaces: spacesCount
    };
}

console.log(analyzeText("Our Compiler 2026 Platform"));

Project 3: Advanced Palindrome Checker (Phrases)

JavaScript โ€” Palindrome Project โ–ถ Run Code
"use strict";

function checkPhrasePalindrome(phrase) {
    const clean = phrase.toLowerCase().replace(/[^a-z0-9]/g, "");
    const rev = clean.split("").reverse().join("");
    return clean === rev;
}

console.log("A man, a plan, a canal: Panama ->", checkPhrasePalindrome("A man, a plan, a canal: Panama")); // true
console.log("Hello World ->", checkPhrasePalindrome("Hello World")); // false

Project 4: Username Validator

JavaScript โ€” Username Validator โ–ถ Run Code
"use strict";

function validateUsername(username) {
    // Rule 1: Length between 4 and 15
    if (username.length < 4 || username.length > 15) {
        return "โŒ Username must be between 4 and 15 characters.";
    }
    
    // Rule 2: Cannot contain spaces
    if (username.includes(" ")) {
        return "โŒ Username cannot contain spaces.";
    }
    
    // Rule 3: Must start with a letter
    const firstChar = username[0].toLowerCase();
    if (firstChar < 'a' || firstChar > 'z') {
        return "โŒ Username must start with a letter.";
    }
    
    return "โœ… Valid Username: @" + username;
}

console.log(validateUsername("ravi_dev"));     // Valid
console.log(validateUsername("123ravi"));      // Invalid start
console.log(validateUsername("ravi nayak"));   // Contains spaces

Project 5: Password Strength Checker

JavaScript โ€” Password Strength โ–ถ Run Code
"use strict";

function checkPasswordStrength(password) {
    let score = 0;
    
    if (password.length >= 8) score++;
    if (/[A-Z]/.test(password)) score++; // Has Uppercase
    if (/[a-z]/.test(password)) score++; // Has Lowercase
    if (/[0-9]/.test(password)) score++; // Has Number
    if (/[^A-Za-z0-9]/.test(password)) score++; // Has Special Char
    
    if (score <= 2) return "๐Ÿ”ด WEAK Password (Add numbers & symbols)";
    if (score <= 4) return "๐ŸŸก MEDIUM Password (Good, but can be stronger)";
    return "๐ŸŸข STRONG Password (Excellent security!)";
}

console.log("pass123:", checkPasswordStrength("pass123"));
console.log("Ravi@2026#Secure:", checkPasswordStrength("Ravi@2026#Secure"));
๐Ÿ’ป Try It Yourself โ€” User Curriculum Code Example

Run this string processing snippet in our live compiler:

JavaScript Strings โ–ถ Run Code
"use strict";

const language = "JavaScript";

console.log("Length:", language.length);
console.log("Uppercase:", language.toUpperCase());
console.log("Includes 'Script':", language.includes("Script"));
console.log(`I am learning ${language}`);
Run Code in Our Compiler โ†’
OC
Written and reviewed by Our Compiler Technical Team ยท Updated for JavaScript ES2026+