Web Development /JavaScript Programming / Lesson
Web Development

JavaScript Strings, Template Literals and String Methods

Learn how JavaScript works with text using strings, template literals and essential string methods such as trim(), includes(), slice(), substring(), replace(), split(), join(), toUpperCase() and toLowerCase().

🎯

Learning Objectives

["Understand what strings are in JavaScript.","Create strings using single quotes, double quotes and backticks.","Understand string indexing and the length property.","Access individual characters in a string.","Use template literals to create dynamic text.","Insert variables and expressions into template literals.","Create multiline strings with template literals.","Understand string immutability.","Convert strings to uppercase and lowercase.","Remove unnecessary whitespace with trim().","Search strings using includes(), startsWith() and endsWith().","Find character positions using indexOf() and lastIndexOf().","Extract parts of strings using slice() and substring().","Replace text using replace() and replaceAll().","Split strings into arrays using split().","Combine array elements into strings using join().","Repeat strings using repeat().","Use padStart() and padEnd() for formatted output.","Convert and process user input safely.","Apply string methods in practical web development projects."]

📖

Lesson Content

Introduction to JavaScript Strings

Text is everywhere in web development. Usernames, emails, passwords, course titles, messages, search queries, addresses and website content are all represented as text.

In JavaScript, text is stored using the string data type.

const name = "Ade";

const course = "Web Development";

const message = "Welcome to Dwallnet Technologies";

JavaScript provides many tools for creating, searching, modifying and formatting strings.

What Is a String?

A string is a sequence of characters used to represent text.

const firstName = "Ade";
const country = "Nigeria";
const message = "Welcome to the course";

Strings can contain letters, numbers, spaces and special characters.

const code = "DW2026";
const phone = "08123456789";
const address = "Agbor, Delta State";

Notice that values such as phone numbers are sometimes intentionally stored as strings because they are identifiers rather than values we intend to calculate with.

Creating Strings

JavaScript provides three common ways to create strings.

Single Quotes

const name = 'Ade';

Double Quotes

const name = "Ade";

Backticks

const name = `Ade`;

Backticks are called template literals and provide additional capabilities that will be covered later in this lesson.

String Length

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

const name = "Ade";

console.log(name.length);

The result is:

3

Spaces are also counted as characters.

const message = "Hello World";

console.log(message.length);

Accessing Characters

Strings use zero-based indexing, similar to arrays.

const name = "Ade";

console.log(name[0]);
console.log(name[1]);
console.log(name[2]);

The output is:

A
d
e

You can also use the at() method.

const name = "Ade";

console.log(name.at(0));
console.log(name.at(-1));

The negative index allows you to access characters from the end.

Strings Are Immutable

JavaScript strings are immutable. This means that individual characters cannot be changed directly.

let name = "Ade";

name[0] = "M";

console.log(name);

The string remains unchanged.

Instead, create a new string:

let name = "Ade";

name = "Mde";

console.log(name);

Most string methods also return a new string rather than modifying the original string.

Concatenating Strings

Concatenation means joining strings together.

const firstName = "Ade";
const lastName = "Johnson";

const fullName = firstName + " " + lastName;

console.log(fullName);

The result is:

Ade Johnson

The + operator can be used to combine strings.

Template Literals

Template literals use backticks and provide a cleaner way to build dynamic strings.

const name = "Ade";
const course = "Web Development";

const message = `Welcome ${name} to ${course}.`;

console.log(message);

The expression inside ${...} is called an interpolation.

Template Literal Expressions

Template literals can contain expressions, not just variables.

const price = 150000;
const discount = 10000;

const finalPrice = price - discount;

const message = `Final course fee: ₦${finalPrice}`;

console.log(message);

Multiline Strings

Template literals can create multiline strings without manually adding newline characters.

const message = `
Welcome to Dwallnet Technologies.

Learn.
Practice.
Build.
`;

console.log(message);

This is useful when generating formatted text dynamically.

toUpperCase()

The toUpperCase() method converts a string to uppercase.

const course = "web development";

console.log(course.toUpperCase());

Result:

WEB DEVELOPMENT

toLowerCase()

The toLowerCase() method converts a string to lowercase.

const course = "WEB DEVELOPMENT";

console.log(course.toLowerCase());

Result:

web development

These methods are useful when normalizing user input.

trim()

User input may contain unnecessary spaces at the beginning or end.

const username = "   Ade   ";

const cleanUsername = username.trim();

console.log(cleanUsername);

trim() removes whitespace from both ends of a string.

trimStart() and trimEnd()

JavaScript also provides methods for removing whitespace from only one side.

const value = "   JavaScript   ";

console.log(value.trimStart());
console.log(value.trimEnd());

includes()

The includes() method checks whether a string contains another string.

const message = "Welcome to Dwallnet Technologies";

console.log(message.includes("Dwallnet"));
console.log(message.includes("Python"));

The results are:

true
false

String matching with includes() is case-sensitive.

startsWith()

The startsWith() method checks whether a string begins with a specified value.

const course = "Web Development";

console.log(course.startsWith("Web"));
console.log(course.startsWith("Development"));

endsWith()

The endsWith() method checks whether a string ends with a specified value.

const email = "student@example.com";

console.log(email.endsWith(".com"));

indexOf()

The indexOf() method returns the position of the first occurrence of a value.

const message = "JavaScript is powerful";

console.log(message.indexOf("Script"));

If the value is not found, indexOf() returns -1.

lastIndexOf()

The lastIndexOf() method returns the position of the last occurrence.

const text = "JavaScript JavaScript";

console.log(text.lastIndexOf("JavaScript"));

slice()

The slice() method extracts part of a string and returns a new string.

const course = "JavaScript";

const part = course.slice(0, 4);

console.log(part);

The result is:

Java

The ending index is not included.

You can also omit the ending index.

const course = "JavaScript";

console.log(course.slice(4));

This returns the remainder of the string starting from index 4.

Negative Values with slice()

Negative indexes count from the end.

const course = "JavaScript";

console.log(course.slice(-6));

This extracts the final six characters.

substring()

The substring() method also extracts characters from a string.

const language = "JavaScript";

console.log(language.substring(0, 4));

substring() and slice() have some differences, particularly in how negative values are handled. Modern code often uses slice() when negative indexes are useful.

replace()

The replace() method replaces part of a string and returns a new string.

const message = "Welcome to PHP";

const updatedMessage = message.replace(
    "PHP",
    "JavaScript"
);

console.log(updatedMessage);

The original string is not modified.

replaceAll()

The replaceAll() method replaces every occurrence of a matching string.

const text = "JavaScript is powerful. JavaScript is popular.";

const updated = text.replaceAll(
    "JavaScript",
    "JS"
);

console.log(updated);

Splitting Strings with split()

The split() method converts a string into an array.

const courses = "HTML,CSS,JavaScript";

const courseList = courses.split(",");

console.log(courseList);

The result is:

["HTML", "CSS", "JavaScript"]

This is useful when processing comma-separated values.

Splitting by Spaces

const sentence = "JavaScript is powerful";

const words = sentence.split(" ");

console.log(words);

The result is an array of words.

Joining Arrays with join()

The join() method does the opposite of split() by combining array elements into a string.

const courses = [
    "HTML",
    "CSS",
    "JavaScript"
];

const result = courses.join(", ");

console.log(result);

The result is:

HTML, CSS, JavaScript

repeat()

The repeat() method repeats a string a specified number of times.

const line = "-".repeat(20);

console.log(line);

This can be useful when creating formatted console output or text-based interfaces.

padStart()

padStart() adds characters to the beginning of a string until it reaches a specified length.

const number = "42";

const formatted = number.padStart(5, "0");

console.log(formatted);

The result is:

00042

padEnd()

padEnd() adds characters to the end of a string.

const code = "DW";

console.log(code.padEnd(6, "0"));

The result is:

DW0000

Comparing Strings

Strings can be compared using comparison operators.

const role = "student";

console.log(role === "student");
console.log(role === "admin");

String comparisons are case-sensitive.

console.log("JavaScript" === "javascript");

The result is false.

Normalizing User Input

When processing user input, it is often useful to normalize the text before comparing it.

const input = "  STUDENT  ";

const role = input.trim().toLowerCase();

console.log(role);

if (role === "student") {
    console.log("Student account");
}

This allows different forms of capitalization and surrounding spaces to be handled consistently.

Checking an Email Domain

String methods can be used for simple application-level checks.

const email = "student@example.com";

if (email.endsWith("@example.com")) {
    console.log("Example domain detected");
}

For production applications, important validation should still be performed appropriately on the server rather than relying only on client-side JavaScript.

Combining String Methods

String methods can be chained together.

const username = "   ADE   ";

const normalizedUsername = username
    .trim()
    .toLowerCase();

console.log(normalizedUsername);

The result is:

ade

Strings and Arrays Together

String and array methods are often used together when processing text.

const sentence = "JavaScript makes websites interactive";

const words = sentence.split(" ");

const uppercaseWords = words.map(
    word => word.toUpperCase()
);

const result = uppercaseWords.join(" ");

console.log(result);

This converts each word to uppercase and then joins the words back into a sentence.

Practical Example: Student Name Formatter

const firstName = "   ade   ";
const lastName = "  JOHNSON ";

const formattedFirstName = firstName
    .trim()
    .toLowerCase();

const formattedLastName = lastName
    .trim()
    .toLowerCase();

const fullName = `${formattedFirstName} ${formattedLastName}`;

console.log(fullName);

This example cleans user input and combines it into a consistent format.

Practical Example: Course Search

const searchInput = "  javascript  ";

const searchTerm = searchInput
    .trim()
    .toLowerCase();

const courses = [
    "JavaScript Fundamentals",
    "Data Analysis",
    "Cyber Security",
    "JavaScript DOM"
];

const matchingCourses = courses.filter(course =>
    course.toLowerCase().includes(searchTerm)
);

console.log(matchingCourses);

This pattern can be used as part of a course search interface.

Practical Example: Creating a Student ID

const year = "2026";
const number = "42";

const studentId =
    `DW-${year}-${number.padStart(4, "0")}`;

console.log(studentId);

The output is:

DW-2026-0042

Escaping Characters

Sometimes a string needs to contain a quote character.

const message = "He said \"Hello\".";

console.log(message);

The backslash is used as an escape character.

Single quotes can also be used when the text contains double quotes:

const message = 'He said "Hello".';

Template literals provide another option:

const message = `He said "Hello".`;

Special Characters

JavaScript strings support escape sequences such as:

  • \n for a new line.
  • \t for a tab.
  • \\ for a backslash.
  • \" for a double quote.
  • \' for a single quote.

String Conversion

Values can be converted to strings using String().

const score = 85;

const scoreText = String(score);

console.log(scoreText);
console.log(typeof scoreText);

The result is a string.

Another common technique is:

const score = 85;

const scoreText = score.toString();

console.log(scoreText);

Use care with toString() because it cannot be called directly on null or undefined.

Checking String Type

The typeof operator can determine whether a value is a string.

const name = "Ade";

console.log(typeof name);

The result is:

string

Common Beginner Mistakes

1. Forgetting That String Matching Is Case-Sensitive

console.log("JavaScript".includes("javascript"));

This returns false.

2. Expecting String Methods to Modify the Original String

const name = "ade";

name.toUpperCase();

console.log(name);

The original string remains unchanged. Store the returned value if you need the result.

const name = "ade";

const upperName = name.toUpperCase();

console.log(upperName);

3. Confusing split() and join()

split() converts a string into an array, while join() combines array elements into a string.

4. Forgetting That Indexes Start at Zero

The first character is at index 0.

Best Practices

  • Use template literals when building strings containing multiple variables.
  • Normalize user input when appropriate before comparing it.
  • Use trim() to remove unwanted surrounding whitespace.
  • Remember that string methods generally return new strings.
  • Use descriptive variable names for text values.
  • Choose the string method that clearly expresses what your code needs to do.
  • Do not rely only on client-side string validation for security-sensitive operations.
  • Use server-side validation when data is submitted to an application backend.
  • Be aware that string comparisons are case-sensitive unless you normalize the values.

Practice Exercise

Create a small JavaScript program that processes a student’s information.

Your program should:

  1. Store the student’s full name in a string.
  2. Remove unnecessary spaces using trim().
  3. Convert the name to a consistent case.
  4. Display the number of characters in the name.
  5. Extract the first name.
  6. Check whether the name contains a specific character.
  7. Create a welcome message using a template literal.
  8. Store several course names in a comma-separated string.
  9. Convert the string into an array using split().
  10. Convert the array back into a readable string using join().

Lesson Summary

Strings are fundamental to JavaScript and are used whenever an application needs to work with text. JavaScript provides a large collection of methods for searching, formatting, extracting and transforming strings.

You have learned about string creation, indexing, length, immutability, concatenation, template literals, case conversion, trimming, searching, slicing, replacing, splitting, joining, padding and string conversion.

These techniques are essential when building forms, search interfaces, dashboards, user profiles, course platforms and applications that process information from users or external systems.

💻

Code Example

const firstName = "   Ade   ";
const lastName = "   Johnson   ";

const cleanFirstName = firstName
    .trim()
    .toLowerCase();

const cleanLastName = lastName
    .trim()
    .toLowerCase();

const fullName = `${cleanFirstName} ${cleanLastName}`;

console.log("Full Name:", fullName);
console.log("Name Length:", fullName.length);

// Create a welcome message
const course = "JavaScript";
const welcomeMessage =
    `Welcome ${fullName} to ${course}!`;

console.log(welcomeMessage);

// Search text
console.log(
    "Contains JavaScript:",
    welcomeMessage.includes("JavaScript")
);

// Course list
const courseText =
    "HTML,CSS,JavaScript,PHP,MySQL";

const courses = courseText.split(",");

console.log("Courses:", courses);

// Convert courses back to text
const courseList = courses.join(" | ");

console.log("Course List:", courseList);

// Student ID
const studentNumber = "42";

const studentId =
    `DW-2026-${studentNumber.padStart(4, "0")}`;

console.log("Student ID:", studentId);

// Course search
const searchInput = " javascript ";

const searchTerm = searchInput
    .trim()
    .toLowerCase();

const matchingCourses = courses.filter(course =>
    course.toLowerCase().includes(searchTerm)
);

console.log("Matching Courses:", matchingCourses);
⭐

Key Takeaways

["Strings are JavaScript values used to represent text.","Strings can be created using single quotes, double quotes or backticks.","Backticks create template literals.","Template literals support variable interpolation and expressions.","The length property returns the number of characters in a string.","String indexes begin at zero.","JavaScript strings are immutable.","toUpperCase() converts text to uppercase.","toLowerCase() converts text to lowercase.","trim() removes whitespace from both ends of a string.","includes() checks whether text contains another value.","startsWith() and endsWith() check the beginning and end of strings.","indexOf() and lastIndexOf() locate text inside a string.","slice() and substring() extract parts of strings.","replace() and replaceAll() replace text.","split() converts a string into an array.","join() combines array elements into a string.","repeat(), padStart() and padEnd() can be used for formatting.","String() and toString() can convert values into text.","String methods are widely used when processing forms, search input and application data."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress