Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Strings Template Literals
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

String Methods and Template Literals

Master text manipulation in JavaScript

Strings are one of the most common data types you'll work with in JavaScript. Whether you're displaying messages to users, processing form input, or manipulating text data, you'll need to know how to work with strings effectively. Let's explore modern string syntax and powerful built-in methods!

String Basics Review

Strings represent text and can be created three ways: single quotes, double quotes, or backticks (template literals).

JAVASCRIPT
// Three ways to create strings
let single = 'Hello';
let double = "Hello";
let template = `Hello`;

// All three work the same for simple strings
console.log(single);   // Hello
console.log(double);   // Hello
console.log(template); // Hello

Strings Are Immutable

Once created, strings cannot be changed. String methods return new strings instead of modifying the original.

JAVASCRIPT
let message = "Hello";

// This doesn't change the original string
message.toUpperCase();
console.log(message);  // Still "Hello"

// You must save the result to use it
let upperMessage = message.toUpperCase();
console.log(upperMessage);  // "HELLO"

// Or reassign
message = message.toUpperCase();
console.log(message);  // "HELLO"

Template Literals (Backticks)

Template literals are the modern way to work with strings. They use backticks (`) and provide powerful features like variable interpolation and multi-line strings.

Variable Interpolation

Embed variables and expressions directly in strings using ${} syntax.

JAVASCRIPT
let name = "Alice";
let age = 25;

// Old way (concatenation)
let message1 = "Hello, my name is " + name + " and I'm " + age + " years old.";

// Modern way (template literal)
let message2 = `Hello, my name is ${name} and I'm ${age} years old.`;

console.log(message1);  // Hello, my name is Alice and I'm 25 years old.
console.log(message2);  // Hello, my name is Alice and I'm 25 years old.

Expression Interpolation

You can put any JavaScript expression inside ${}.

JAVASCRIPT
let price = 50;
let quantity = 3;

// Calculations inside template literals
let total = `Total: $${price * quantity}`;
console.log(total);  // Total: $150

// Function calls
let greeting = `Hello, ${name.toUpperCase()}!`;
console.log(greeting);  // Hello, ALICE!

// Conditional expressions
let age = 20;
let status = `You are ${age >= 18 ? 'an adult' : 'a minor'}`;
console.log(status);  // You are an adult

Multi-Line Strings

Template literals preserve line breaks, making multi-line strings easy.

JAVASCRIPT
// Old way (needs \n)
let oldPoem = "Roses are red\nViolets are blue\nJavaScript is awesome\nAnd so are you";

// Modern way (natural line breaks)
let newPoem = `
Roses are red
Violets are blue
JavaScript is awesome
And so are you
`;

console.log(newPoem);

See how template literals simplify string creation

Concatenation (Old)

// Old concatenation
let firstName = "John";
let lastName = "Doe";
let age = 30;
let city = "New York";

let profile = "Name: " + firstName + " " + lastName + "\n" +
              "Age: " + age + "\n" +
              "City: " + city;

console.log(profile);
Output:
Not run yet...

Template Literal (Modern)

// Modern template literal
let firstName = "John";
let lastName = "Doe";
let age = 30;
let city = "New York";

let profile = `Name: ${firstName} ${lastName}
Age: ${age}
City: ${city}`;

console.log(profile);
Output:
Not run yet...

Template Literals Practice

Experiment with modern string syntax

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

String Properties

length Property

The length property returns the number of characters in a string.

JAVASCRIPT
let message = "Hello, World!";
console.log(message.length);  // 13

let empty = "";
console.log(empty.length);  // 0

let spaces = "   ";
console.log(spaces.length);  // 3 (spaces count!)

// Useful for validation
let password = "abc123";
if (password.length < 8) {
  console.log("Password too short! Minimum 8 characters.");
}

Accessing Individual Characters

JAVASCRIPT
let text = "JavaScript";

// Using bracket notation (like arrays)
console.log(text[0]);  // J
console.log(text[4]);  // S
console.log(text[9]);  // t

// Using charAt() method
console.log(text.charAt(0));  // J
console.log(text.charAt(4));  // S

// Out of bounds
console.log(text[100]);       // undefined
console.log(text.charAt(100)); // "" (empty string)

// Last character
let lastIndex = text.length - 1;
console.log(text[lastIndex]);  // t

Case Conversion Methods

JAVASCRIPT
let text = "Hello World";

// Convert to uppercase
console.log(text.toUpperCase());  // HELLO WORLD

// Convert to lowercase
console.log(text.toLowerCase());  // hello world

// Original string unchanged
console.log(text);  // Hello World

// Common use: case-insensitive comparison
let input = "JAVASCRIPT";
let target = "javascript";

if (input.toLowerCase() === target.toLowerCase()) {
  console.log("Match!"); // This will execute
}

Practical Use Cases

JAVASCRIPT
// Email validation (emails are case-insensitive)
let email = "User@Example.COM";
let normalizedEmail = email.toLowerCase();
console.log(normalizedEmail);  // user@example.com

// Display names
let firstName = "john";
let capitalized = firstName.charAt(0).toUpperCase() + firstName.slice(1);
console.log(capitalized);  // John

// Acronyms
let title = "hypertext markup language";
let acronym = title.split(" ")
  .map(word => word[0].toUpperCase())
  .join("");
console.log(acronym);  // HTML

Searching and Checking Strings

includes() - Check if String Contains Substring

JAVASCRIPT
let message = "JavaScript is awesome!";

// Check if string contains a word
console.log(message.includes("JavaScript"));  // true
console.log(message.includes("Python"));      // false

// Case-sensitive!
console.log(message.includes("javascript"));  // false

// Case-insensitive check
let search = "AWESOME";
console.log(message.toLowerCase().includes(search.toLowerCase()));  // true

// Practical use
let comment = "This is spam and fake";
if (comment.includes("spam") || comment.includes("fake")) {
  console.log("Comment flagged!");
}

startsWith() and endsWith()

JAVASCRIPT
let filename = "document.pdf";

// Check how string starts
console.log(filename.startsWith("doc"));  // true
console.log(filename.startsWith("Doc"));  // false

// Check how string ends
console.log(filename.endsWith(".pdf"));   // true
console.log(filename.endsWith(".txt"));   // false

// Practical: file type validation
if (filename.endsWith(".pdf") || filename.endsWith(".doc")) {
  console.log("Valid document format");
}

// URL validation
let url = "https://example.com";
if (url.startsWith("https://")) {
  console.log("Secure URL");
}

indexOf() and lastIndexOf()

JAVASCRIPT
let text = "Hello World, Hello Universe";

// Find first occurrence
console.log(text.indexOf("Hello"));       // 0
console.log(text.indexOf("World"));       // 6
console.log(text.indexOf("Goodbye"));     // -1 (not found)

// Find last occurrence
console.log(text.lastIndexOf("Hello"));   // 13

// Check if substring exists
if (text.indexOf("World") !== -1) {
  console.log("Found 'World'");
}

// Modern alternative (cleaner)
if (text.includes("World")) {
  console.log("Found 'World'");
}

Extracting Parts of Strings

slice() - Extract a Section

JAVASCRIPT
let text = "JavaScript";

// slice(start, end)
console.log(text.slice(0, 4));   // Java
console.log(text.slice(4));      // Script (from 4 to end)
console.log(text.slice(4, 10));  // Script

// Negative indices (count from end)
console.log(text.slice(-6));     // Script (last 6 characters)
console.log(text.slice(-6, -2)); // Scri

// Get last 3 characters
console.log(text.slice(-3));     // ipt

substring() - Similar to slice

JAVASCRIPT
let text = "JavaScript";

// substring(start, end)
console.log(text.substring(0, 4));  // Java
console.log(text.substring(4));     // Script

// Note: substring doesn't support negative indices
console.log(text.substring(-3));    // JavaScript (treats -3 as 0)

// slice is generally preferred over substring

Practical Examples

JAVASCRIPT
// Extract domain from email
let email = "user@example.com";
let atIndex = email.indexOf("@");
let domain = email.slice(atIndex + 1);
console.log(domain);  // example.com

// Get file extension
let filename = "document.pdf";
let dotIndex = filename.lastIndexOf(".");
let extension = filename.slice(dotIndex);
console.log(extension);  // .pdf

// Truncate long text
let longText = "This is a very long text that needs to be shortened";
let preview = longText.slice(0, 20) + "...";
console.log(preview);  // This is a very long...

Modifying Strings

trim(), trimStart(), trimEnd()

JAVASCRIPT
let text = "   Hello World   ";

// Remove whitespace from both ends
console.log(text.trim());       // "Hello World"

// Remove from start only
console.log(text.trimStart());  // "Hello World   "

// Remove from end only
console.log(text.trimEnd());    // "   Hello World"

// Practical: clean user input
let userInput = "  john@example.com  ";
let cleanEmail = userInput.trim().toLowerCase();
console.log(cleanEmail);  // "john@example.com"

replace() and replaceAll()

JAVASCRIPT
let text = "Hello World, Hello Universe";

// Replace first occurrence
console.log(text.replace("Hello", "Hi"));  // Hi World, Hello Universe

// Replace all occurrences (ES2021)
console.log(text.replaceAll("Hello", "Hi"));  // Hi World, Hi Universe

// Case-insensitive replace with regex
let message = "JavaScript is GREAT! JavaScript rocks!";
let newMessage = message.replace(/javascript/gi, "JS");
console.log(newMessage);  // JS is GREAT! JS rocks!

// Practical: clean up text
let dirty = "This    has    extra    spaces";
let clean = dirty.replace(/\s+/g, " ");
console.log(clean);  // This has extra spaces

repeat()

JAVASCRIPT
let star = "*";

// Repeat a string
console.log(star.repeat(5));  // *****

// Create patterns
let line = "-".repeat(20);
console.log(line);  // --------------------

// Indentation
let indent = " ".repeat(4);
console.log(indent + "Indented text");

// Loading indicator
for (let i = 1; i <= 3; i++) {
  console.log("Loading" + ".".repeat(i));
}
// Loading.
// Loading..
// Loading...

Splitting and Joining Strings

split() - String to Array

JAVASCRIPT
let sentence = "JavaScript is awesome";

// Split into words
let words = sentence.split(" ");
console.log(words);  // ["JavaScript", "is", "awesome"]

// Split into characters
let text = "Hello";
let chars = text.split("");
console.log(chars);  // ["H", "e", "l", "l", "o"]

// Split by comma
let csv = "apple,banana,orange";
let fruits = csv.split(",");
console.log(fruits);  // ["apple", "banana", "orange"]

// Limit number of splits
let limited = sentence.split(" ", 2);
console.log(limited);  // ["JavaScript", "is"]

join() - Array to String

JAVASCRIPT
let words = ["JavaScript", "is", "awesome"];

// Join with space
console.log(words.join(" "));   // JavaScript is awesome

// Join with comma
console.log(words.join(","));   // JavaScript,is,awesome

// Join with nothing
console.log(words.join(""));    // JavaScriptisawesome

// Join with custom separator
console.log(words.join(" - ")); // JavaScript - is - awesome

Practical Examples

JAVASCRIPT
// Reverse a string
let text = "JavaScript";
let reversed = text.split("").reverse().join("");
console.log(reversed);  // tpircSavaJ

// Count words
let sentence = "The quick brown fox jumps";
let wordCount = sentence.split(" ").length;
console.log(wordCount);  // 5

// Create initials
let fullName = "John Michael Doe";
let initials = fullName
  .split(" ")
  .map(word => word[0])
  .join("");
console.log(initials);  // JMD

// Format phone number
let digits = "1234567890";
let formatted = digits.split("").join("-");
console.log(formatted);  // 1-2-3-4-5-6-7-8-9-0

// Better phone format
let phone = "1234567890";
let parts = [phone.slice(0,3), phone.slice(3,6), phone.slice(6)];
console.log(parts.join("-"));  // 123-456-7890

Practical String Examples

Example 1: Input Validation

JAVASCRIPT
function validateUsername(username) {
  // Remove whitespace
  username = username.trim();
  
  // Check length
  if (username.length < 3) {
    return "Username too short (minimum 3 characters)";
  }
  
  if (username.length > 20) {
    return "Username too long (maximum 20 characters)";
  }
  
  // Check for spaces
  if (username.includes(" ")) {
    return "Username cannot contain spaces";
  }
  
  // Check for special characters (simple check)
  if (!/^[a-zA-Z0-9_]+$/.test(username)) {
    return "Username can only contain letters, numbers, and underscores";
  }
  
  return "Valid username!";
}

console.log(validateUsername("  john_doe  "));  // Valid username!
console.log(validateUsername("ab"));            // Username too short
console.log(validateUsername("john doe"));      // Username cannot contain spaces

Example 2: Text Formatting

JAVASCRIPT
function formatName(firstName, lastName) {
  // Clean and capitalize
  let first = firstName.trim().toLowerCase();
  let last = lastName.trim().toLowerCase();
  
  // Capitalize first letter
  first = first.charAt(0).toUpperCase() + first.slice(1);
  last = last.charAt(0).toUpperCase() + last.slice(1);
  
  return `${first} ${last}`;
}

console.log(formatName("  jOHN  ", "  dOE  "));  // John Doe

function createSlug(title) {
  return title
    .toLowerCase()
    .trim()
    .replace(/\s+/g, "-")      // Replace spaces with hyphens
    .replace(/[^a-z0-9-]/g, "") // Remove special characters
    .replace(/-+/g, "-");       // Replace multiple hyphens with single
}

console.log(createSlug("Hello World! How are you?"));  // hello-world-how-are-you

Example 3: Data Extraction

JAVASCRIPT
function parseEmail(email) {
  email = email.trim().toLowerCase();
  
  let atIndex = email.indexOf("@");
  
  if (atIndex === -1) {
    return { valid: false };
  }
  
  let username = email.slice(0, atIndex);
  let domain = email.slice(atIndex + 1);
  
  return {
    valid: true,
    username: username,
    domain: domain,
    fullEmail: email
  };
}

let result = parseEmail("  John.Doe@Example.COM  ");
console.log(result);
// {
//   valid: true,
//   username: "john.doe",
//   domain: "example.com",
//   fullEmail: "john.doe@example.com"
// }

Text Processing Tool

See multiple string methods in action

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Method Chaining

Since string methods return new strings, you can chain multiple methods together.

JAVASCRIPT
let input = "  HELLO WORLD  ";

// Chain multiple methods
let result = input
  .trim()           // "HELLO WORLD"
  .toLowerCase()    // "hello world"
  .replace(" ", "-"); // "hello-world"

console.log(result);  // hello-world

// More complex chaining
let email = "  User@EXAMPLE.com  ";
let normalized = email.trim().toLowerCase();
console.log(normalized);  // user@example.com

// Processing user input
let userInput = "  JavaScript   is   AWESOME!  ";
let processed = userInput
  .trim()
  .replace(/\s+/g, " ")     // Normalize spaces
  .toLowerCase()
  .split(" ")
  .join("-");

console.log(processed);  // javascript-is-awesome!

Key Takeaways

  • Use template literals (`) for modern string creation
  • Embed variables with ${} syntax
  • Strings are immutable—methods return new strings
  • length property gives character count
  • toUpperCase() and toLowerCase() convert case
  • includes(), startsWith(), endsWith() for searching
  • slice() extracts parts of strings
  • trim() removes whitespace from ends
  • replace() and replaceAll() substitute text
  • split() converts string to array
  • Chain methods together for complex operations
  • Always clean and validate user input

What's Next?

You now have a solid understanding of how to work with strings in JavaScript! String manipulation is a fundamental skill you'll use constantly—from form validation to data processing to building user interfaces.

In the next lesson, we'll explore Type Conversion and Coercion—learning how JavaScript converts between different data types, both explicitly (when you tell it to) and implicitly (when it happens automatically). Understanding this will help you avoid common bugs and write more predictable code.

💪 Practice Challenge:

Before moving on, try building:

  1. A function that takes a full name and returns initials
  2. A password validator (minimum length, must contain uppercase, lowercase, and number)
  3. A function that creates a URL slug from a title (lowercase, hyphens instead of spaces)
  4. A text truncator that adds "..." if text exceeds a certain length
  5. An email masker that shows only first 3 characters before @ (j***@example.com)

Test Your Understanding

Question 1 / 4

What's the modern way to create strings with embedded variables?

Score: 0 / 0

Mastering JavaScript strings! 📝✨

Previous
Comments and Code Organization
Next
Type Conversion and Coercion

Keep Learning JavaScript

Join 2,000+ developers mastering JavaScript fundamentals. New tutorials weekly - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo