LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Strings, Template Literals and String Methods in JavaScript

A string is text written inside quotes. We use strings for names, messages, addresses, and search values. Template literals help us insert variables directly into text. String methods are built-in functions that help us change, search, and check text easily. 2

Strings, Template Literals and String Methods in JavaScript

Quick Answer: A string stores text in JavaScript. Template literals make it easier to combine text with variables. String methods help us search, change, extract and check text.

We will use a restaurant order to understand these concepts. You will build readable order messages and process customer input.

1. The Problem: Building Customer Messages Without Template Literals

Imagine you manage a restaurant in Bengaluru. You receive 500 orders every day. Each order needs a customer name, item and amount.

How will you create clear messages for every customer? Think about this before looking at the solution.

Creating Messages With String Concatenation

String concatenation means joining two or more strings. We can use the + operator for this.

Example 1: Creating three restaurant order messages

const customer1 = "Priya";
const item1 = "Masala Dosa";
const amount1 = 80;

const customer2 = "Ravi";
const item2 = "Idli";
const amount2 = 50;

const customer3 = "Lakshmi";
const item3 = "Meals";
const amount3 = 120;

console.log("Customer: " + customer1 + ", Item: " + item1 + ", Amount: Rs. " + amount1);
console.log("Customer: " + customer2 + ", Item: " + item2 + ", Amount: Rs. " + amount2);
console.log("Customer: " + customer3 + ", Item: " + item3 + ", Amount: Rs. " + amount3);

Expected output

Customer: Priya, Item: Masala Dosa, Amount: Rs. 80
Customer: Ravi, Item: Idli, Amount: Rs. 50
Customer: Lakshmi, Item: Meals, Amount: Rs. 120

This works, but it gets hard to manage. Every new message needs repeated concatenation and careful spacing.

What Goes Wrong When Messages Grow?

  1. Repeated code: We write similar message expressions again.
  2. Missing spaces: Joining text can produce incorrect formatting.
  3. Harder changes: Adding fields makes expressions longer.
  4. Lower readability: Long messages become difficult to understand.

Now think about 500 orders. Small changes can affect many message expressions.

The Solution: Use Template Literals

Template literals let us place variables directly inside text. They use backticks instead of single or double quotes.

Example 2: Creating the same messages with template literals

const orders = [
  { customer: "Priya", item: "Masala Dosa", amount: 80 },
  { customer: "Ravi", item: "Idli", amount: 50 },
  { customer: "Lakshmi", item: "Meals", amount: 120 }
];

orders.forEach((order) => {
  const message = `Customer: ${order.customer}, Item: ${order.item}, Amount: Rs. ${order.amount}`;
  console.log(message);
});

Expected output

Customer: Priya, Item: Masala Dosa, Amount: Rs. 80
Customer: Ravi, Item: Idli, Amount: Rs. 50
Customer: Lakshmi, Item: Meals, Amount: Rs. 120
String concatenation compared with template literals
Without template literals With template literals
Uses the + operator repeatedly. Uses ${...} placeholders.
Spaces need careful handling. Spaces appear naturally in the text.
Long expressions can become hard to read. Long messages are easier to format.
Multiline text needs special handling. Supports multiline text directly.

The Idea to Remember

  • String = text stored inside quotes.
  • Concatenation = joining strings together.
  • Template literal = text written using backticks.
  • Interpolation = placing an expression inside ${...}.

2. Understanding Strings in JavaScript

A string is a sequence of text characters. We use strings for names, messages and addresses.

Three Ways to Create Strings

JavaScript supports single quotes, double quotes and backticks.

Example 3: Creating restaurant details

const restaurantName = 'Bengaluru Food Corner';
const location = "Indiranagar";
const welcomeMessage = `Welcome to ${restaurantName}`;

console.log(restaurantName);
console.log(location);
console.log(welcomeMessage);

Expected output

Bengaluru Food Corner
Indiranagar
Welcome to Bengaluru Food Corner

All three forms create strings. Backticks also support interpolation and multiline text.

Strings Are Immutable

Immutable means the original value cannot be changed directly. String methods return new strings instead.

Example 4: Checking string immutability

let itemName = "Masala Dosa";

itemName.toUpperCase();

console.log(itemName);

const updatedName = itemName.toUpperCase();

console.log(updatedName);

Expected output

Masala Dosa
MASALA DOSA

Remember: Calling toUpperCase() does not change the original string. Store its returned value when you need the changed text.

3. Template Literals in JavaScript

Template literals use backticks: `. They support expressions, multiline text and readable formatting.

String Interpolation

Interpolation means placing a variable or expression inside a string. Use the ${} syntax.

Example 5: Adding order details and calculating a total

const customer = "Priya";
const item = "Masala Dosa";
const quantity = 2;
const price = 80;

const total = quantity * price;

const message = `Hello ${customer},
Your order is ${item}.
Quantity: ${quantity}
Total: Rs. ${total}`;

console.log(message);

Expected output

Hello Priya,
Your order is Masala Dosa.
Quantity: 2
Total: Rs. 160

Expressions Inside Template Literals

You can place calculations and function calls inside placeholders. JavaScript evaluates each expression before creating the final string.

Example 6: Calculating a restaurant bill

const foodAmount = 250;
const deliveryCharge = 30;

const bill = `Final amount: Rs. ${foodAmount + deliveryCharge}`;

console.log(bill);

Expected output

Final amount: Rs. 280

Multiline Strings

Template literals preserve line breaks. You do not need repeated \n characters.

Example 7: Printing a restaurant receipt

const receipt = `BENGALURU FOOD CORNER
---------------------
Customer: Ravi
Item: Idli
Amount: Rs. 50
Status: Paid
---------------------`;

console.log(receipt);

Expected output

BENGALURU FOOD CORNER
---------------------
Customer: Ravi
Item: Idli
Amount: Rs. 50
Status: Paid
---------------------

4. How Template Literals Work Internally

Look at how order data becomes a final customer message. Each stage has one clear responsibility.

Template Literal Processing Flow
Restaurant order: Priya orders two Masala Dosas
STAGE 01 Order Data Priya · Masala Dosa Customer and item values are available.
STAGE 02 Template String `Hello ${customer}` Backticks define the template.
STAGE 03 Interpolation ${quantity * price} JavaScript evaluates each expression.
STAGE 04 Final Message Hello Priya · Rs. 160 The completed string is ready.
Generated customer message Hello Priya, your order total is Rs. 160.

The animation follows order data through template creation, interpolation and final message generation.

5. Important JavaScript String Methods

String methods help us work with text. They can search, extract, replace and check string values.

1. length

Returns the number of UTF-16 code units in a string. It is a property, not a method.

Example 8: Checking the item name length

const item = "Masala Dosa";

console.log(item.length);

Expected output

11

2. toUpperCase() and toLowerCase()

These methods return uppercase and lowercase versions of a string.

Example 9: Formatting an order status

const status = "order confirmed";

console.log(status.toUpperCase());
console.log(status.toLowerCase());

Expected output

ORDER CONFIRMED
order confirmed

3. trim(), trimStart() and trimEnd()

These methods remove whitespace from both ends or one end. They do not remove spaces between words.

Example 10: Cleaning customer input

const customerInput = "   Priya   ";

console.log(customerInput.trim());
console.log(customerInput.trimStart());
console.log(customerInput.trimEnd());

Expected output

Priya
Priya   
   Priya

4. includes(), startsWith() and endsWith()

These methods check whether a string contains or starts with specific text. They return Boolean values.

Example 11: Checking an order description

const order = "Priya ordered Masala Dosa";

console.log(order.includes("Dosa"));
console.log(order.startsWith("Priya"));
console.log(order.endsWith("Dosa"));

Expected output

true
true
true

5. indexOf() and lastIndexOf()

These methods return the position of matching text. They return -1 when no match exists.

Example 12: Finding text inside an order

const order = "Dosa, Idli, Dosa";

console.log(order.indexOf("Dosa"));
console.log(order.lastIndexOf("Dosa"));
console.log(order.indexOf("Meals"));

Expected output

0
12
-1

6. slice()

Returns a selected part of a string. The ending position is not included.

Example 13: Extracting part of an order ID

const orderId = "ORD-BLR-2026-105";

console.log(orderId.slice(0, 3));
console.log(orderId.slice(4, 7));
console.log(orderId.slice(-3));

Expected output

ORD
BLR
105

7. replace() and replaceAll()

replace() replaces the first matching occurrence for a string search. replaceAll() replaces every matching occurrence.

Example 14: Updating an item name

const menu = "Dosa, Idli, Dosa";

console.log(menu.replace("Dosa", "Rava Dosa"));
console.log(menu.replaceAll("Dosa", "Rava Dosa"));

Expected output

Rava Dosa, Idli, Dosa
Rava Dosa, Idli, Rava Dosa

8. split()

Splits a string into an array using a separator. An array stores multiple values in one variable.

Example 15: Splitting a menu list

const menu = "Dosa,Idli,Meals";

const items = menu.split(",");

console.log(items);
console.log(items.length);

Expected output

[ 'Dosa', 'Idli', 'Meals' ]
3

9. concat()

Joins strings and returns a new string. The + operator or template literals are often easier to read.

Example 16: Joining customer details

const firstName = "Priya";
const city = "Bengaluru";

const details = firstName.concat(" - ", city);

console.log(details);

Expected output

Priya - Bengaluru

10. repeat()

Returns a new string containing the original text repeated a given number of times.

Example 17: Printing a receipt separator

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

console.log(separator);

Expected output

--------------------

6. Visual Guide: Choosing the Right String Method

Different methods solve different text problems. This guide groups common operations by their purpose.

Restaurant Text Processing Map
Choose a method based on the operation you need
Clean text trim() Remove extra spaces around customer input.
Check text includes() Check whether an order contains an item.
Extract text slice() Get a part of an order reference.
Change text replaceAll() Replace matching item names.
Split text split() Turn a menu string into an array.
Format text toUpperCase() Display order status in uppercase.
Processing example: Clean customer input, check the item, then format the final order message.

The highlighted method cards cycle through common restaurant text-processing tasks automatically.

7. Common String Mistakes and Best Practices

Mistake 1: Using Quotes Instead of Backticks

Variable interpolation does not work inside ordinary quoted strings.

Wrong and correct approaches

const customer = "Priya";

// Wrong: this prints the placeholder as plain text.
console.log("Hello ${customer}");

// Correct: backticks enable interpolation.
console.log(`Hello ${customer}`);

Expected output

Hello ${customer}
Hello Priya

Mistake 2: Forgetting to Store a Returned String

String methods do not change the original value. Save the returned result when needed.

let status = "pending";

status.toUpperCase();
console.log(status);

status = status.toUpperCase();
console.log(status);

Expected output

pending
PENDING

Mistake 3: Confusing slice() With the Ending Position

The second argument is the ending index. That position is excluded.

const item = "Masala Dosa";

console.log(item.slice(0, 6));

Expected output

Masala

Mistake 4: Assuming String Search Ignores Case

String searches are case-sensitive. Convert the text when case-insensitive matching is needed.

const item = "Masala Dosa";

console.log(item.includes("dosa"));
console.log(item.toLowerCase().includes("dosa"));

Expected output

false
true

Mistake 5: Treating User Input as Already Clean

Customer input can contain unwanted spaces. Clean it before comparing values.

const enteredItem = "  Masala Dosa  ";
const cleanItem = enteredItem.trim();

console.log(cleanItem === "Masala Dosa");

Expected output

true

Best Practices

  • Prefer template literals for readable dynamic messages.
  • Use trim() before checking user-entered text.
  • Remember that string methods return new values.
  • Choose slice() when you need a clear substring range.
  • Use includes() for simple substring checks.
  • Do not assume case-sensitive searches match different letter cases.
  • Use Intl.NumberFormat when formatting real currency values.

8. Real-World Example: Build a Restaurant Order Receipt

Now combine template literals and string methods. We will clean customer input and create a receipt.

Example 18: Complete restaurant receipt generator

const customerInput = "  priya  ";
const itemInput = "masala dosa";
const quantity = 2;
const price = 80;

const customer = customerInput
  .trim()
  .replace("p", "P");

const item = itemInput
  .trim()
  .replace("m", "M");

const total = quantity * price;

const receipt = `BENGALURU FOOD CORNER
-------------------------
Customer: ${customer}
Item: ${item}
Quantity: ${quantity}
Price: Rs. ${price}
Total: Rs. ${total}
Status: PAID
-------------------------`;

console.log(receipt);

Expected output

BENGALURU FOOD CORNER
-------------------------
Customer: Priya
Item: Masala dosa
Quantity: 2
Price: Rs. 80
Total: Rs. 160
Status: PAID
-------------------------

Production note: This example uses simple sample data. Real applications should validate input and handle missing values. Use proper locale-aware formatting for currency and customer-facing receipts.

9. Interview Questions and Answers

1. What is a string in JavaScript?

What the interviewer expects: A clear definition and one important property.

Strong answer: A string is a primitive data type used to store text. We can create it using single quotes, double quotes or backticks. Strings are immutable, so string methods return new strings.

2. What is the difference between normal strings and template literals?

Strong answer: Normal strings use single or double quotes. Template literals use backticks. They support interpolation and multiline text. I use them when building readable messages, such as restaurant receipts.

3. What is string interpolation?

Strong answer: String interpolation means placing expressions inside a template literal. We use the ${} syntax. JavaScript evaluates the expression and adds its result to the string.

4. Are JavaScript strings mutable?

Strong answer: No. JavaScript strings are immutable. A method like toUpperCase() returns a new string. It does not change the original string.

5. What is the difference between slice() and substring()?

Strong answer: Both extract part of a string. slice() supports negative indexes. substring() treats negative arguments as zero and swaps arguments when the first is greater than the second.

6. What is the difference between replace() and replaceAll()?

Strong answer: With a string search value, replace() changes the first match. replaceAll() changes every match. Both return a new string.

7. Is length a method?

Strong answer: No. length is a property. We access it without parentheses. It returns the number of UTF-16 code units, not always the number of user-perceived characters.

Junior, Senior and Architect Expectations

  • Junior: Explain quotes, backticks and common string methods.
  • Senior: Explain immutability, case sensitivity and input cleaning.
  • Architect: Discuss safe output encoding, localization and text handling at scale.

10. Hands-On Practice

Beginner: Format a Customer Name

Given " ravi ", remove surrounding spaces. Then display the name in uppercase.

Expected result: RAVI

Intermediate: Search a Restaurant Menu

Given "Dosa,Idli,Meals,Poori", split the menu into an array. Check whether it includes Meals.

Expected result: An array with four items, followed by true.

Advanced: Generate a Customer Receipt

Create a receipt using customer name, item, quantity and price. Use template literals for the final message.

Expected result: A multiline receipt with the calculated total.

Try This Challenge

Write a function that accepts an order description. Clean its spaces and convert it to lowercase. Check whether it contains the word dosa. Return a clear order message using a template literal.

11. Quick Summary

  • Strings store text and are immutable.
  • Template literals use backticks and support interpolation.
  • String methods help search, clean, extract and replace text.
  • Always store a method's returned value when you need it.
  • Use readable strings when creating messages and receipts.

12. Frequently Asked Questions

Can template literals contain multiple lines?

Yes. Line breaks inside backticks are preserved in the resulting string.

Can I use a function inside a template literal?

Yes. You can call a function inside ${}. Its returned value becomes part of the string.

Does trim() remove spaces between words?

No. It removes whitespace from the beginning and end only.

Does slice() change the original string?

No. It returns a new string containing the selected part.

Are strings and arrays the same?

No. A string stores text. An array stores a collection of values. The split() method can convert a string into an array.

13. Next Steps and Community

Try It Yourself: Build a small restaurant receipt generator. Add customer details and format each order clearly.

Explore Further: Read the official JavaScript String documentation on MDN. Also explore Template Literals on MDN.

Share Your Knowledge: Share your solution and discuss other ways to process strings. Help other learners understand the examples.

Keep practising, write clean code and build useful JavaScript applications.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.