Tutorials / JavaScript Fundamentals / Strings and template literals

Strings and template literals

13 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

Strings are everywhere

Names, messages, URLs, form input and API data are all strings. You will work with them constantly, so it is worth knowing the main tools well.

A string is a sequence of characters. You write it with single quotes, double quotes or backticks.

const single = 'Lahore';
const double = "Pakistan";
const backtick = `Punjab`;

Pick single or double quotes and stay consistent. Backticks are special, and we will get to them shortly.

Length and character access

const word = "JavaScript";
console.log(word.length);    // 10
console.log(word[0]);        // "J"
console.log(word[4]);        // "S"
console.log(word.at(-1));    // "t"  last character

Positions start at 0, not 1. The first character is at index 0. The at() method accepts negative numbers to count from the end, which is neat for the last character.

Strings are immutable. You cannot change a character in place. word[0] = "j" silently does nothing. Every string method returns a new string and leaves the original alone.

Useful string methods

const text = "  Learn JavaScript Step by Step  ";

console.log(text.trim());                 // "Learn JavaScript Step by Step"
console.log(text.toUpperCase());          // "  LEARN JAVASCRIPT STEP BY STEP  "
console.log(text.toLowerCase());
console.log(text.includes("Script"));     // true
console.log(text.startsWith("  Learn"));  // true
console.log(text.indexOf("Java"));        // 8
console.log(text.trim().slice(0, 5));     // "Learn"
console.log(text.trim().replace("Step", "Stage")); // replaces first match only
console.log(text.trim().replaceAll("Step", "Stage"));
console.log("red,green,blue".split(","));  // ["red", "green", "blue"]
console.log(["a", "b", "c"].join("-"));    // "a-b-c"
console.log("ha".repeat(3));               // "hahaha"
console.log("7".padStart(3, "0"));         // "007"

Here is a quick guide to the ones I use most.

MethodWhat it does
trim()Removes spaces from both ends
includes(x)True if the text contains x
indexOf(x)Position of x, or -1 if not found
slice(start, end)Cuts out a part. The end is not included
split(sep)Turns a string into an array
replace / replaceAllSwaps text
padStart(n, ch)Pads to a length, handy for times like 07:05

Notice the chaining in text.trim().slice(0, 5). Each method returns a string, so you can call the next method straight on the result.

Escape characters

If your text contains the same quote you used to open it, put a backslash in front.

const a = 'It\'s fine';
const b = "She said \"hello\"";
const c = "Line one\nLine two";   // \n is a new line
const d = "Column1\tColumn2";     // \t is a tab
const e = "C:\\Users\\Ghulam";    // \\ is a single backslash

Mixing the quote type is often simpler: "It's fine" needs no escape.

Template literals

Backticks give you template literals. They do two useful things.

First, you can put any expression inside ${ } and its value is placed in the text:

const name = "Ali";
const items = 3;
const price = 450;

console.log(`Hello, ${name}!`);
console.log(`You bought ${items} items for Rs. ${items * price}.`);

The output is Hello, Ali! and You bought 3 items for Rs. 1350.. Compare this with the old way: "You bought " + items + " items for Rs. " + (items * price) + ".". It is harder to read and easy to get wrong. I use template literals for nearly all text that has a variable in it.

Second, template literals can span several lines without any \n:

const message = `Dear ${name},

Your order is ready.
Thank you.`;
console.log(message);

The line breaks in your code become line breaks in the string. Be careful with indentation, because extra spaces at the start of lines become part of the text.

Comparing and sorting strings

Strings are compared by their character codes, so uppercase letters come before lowercase ones:

console.log("apple" === "apple");  // true
console.log("Apple" === "apple");  // false
console.log("a" < "b");            // true
console.log("Zebra" < "apple");    // true (capital Z comes before lowercase a)

For case-insensitive checks, convert both sides first: a.toLowerCase() === b.toLowerCase(). For sorting human text such as names, a.localeCompare(b) is better than <.

Common mistakes

  • Expecting slice to include the end. "hello".slice(0, 2) is "he", not "hel".
  • Ignoring the return value. text.toUpperCase(); on its own does nothing useful. You must store the result: text = text.toUpperCase().
  • Using replace and expecting all matches. replace changes only the first match. Use replaceAll.
  • Mixing quotes in template literals. Use backticks, not single quotes, if you want ${} to work. 'Hello ${name}' prints the characters literally.
  • **Forgetting that indexOf returns -1.** if (text.indexOf("x")) is wrong. Use includes.

Try it yourself

  1. Take " hussotech.com ", remove the spaces, make it upper case and print its length.
  2. Use a template literal to print Ali is 25 years old and lives in Lahore from three variables.
  3. Turn "2025-06-15" into an array with split("-") and print the month.
  4. Write code that pads the numbers 1 to 5 with leading zeros so they print as 001 to 005.
javascript
const text = "  Learn JavaScript Step by Step  ";

console.log(text.trim());                 // "Learn JavaScript Step by Step"
console.log(text.toUpperCase());          // "  LEARN JAVASCRIPT STEP BY STEP  "
console.log(text.toLowerCase());
console.log(text.includes("Script"));     // true
console.log(text.startsWith("  Learn"));  // true
console.log(text.indexOf("Java"));        // 8
console.log(text.trim().slice(0, 5));     // "Learn"
console.log(text.trim().replace("Step", "Stage")); // replaces first match only
console.log(text.trim().replaceAll("Step", "Stage"));
console.log("red,green,blue".split(","));  // ["red", "green", "blue"]
console.log(["a", "b", "c"].join("-"));    // "a-b-c"
console.log("ha".repeat(3));               // "hahaha"
console.log("7".padStart(3, "0"));         // "007"

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account