JavaScriptBeginner

JavaScript Strings: Methods, Indexing and Template Literals

Learn to create, read, search, slice, clean and format text in JavaScript using string methods and template literals, with practical examples.

All JavaScript lessons

What you will learn

Almost every website works with text: names, emails, search boxes, messages, titles. In JavaScript, text is stored in a string. In this lesson you will learn how to create strings, read single characters, build text with template literals, and use the most useful string methods to search, cut, replace, clean and format text.

What is a string?

A string is a sequence of characters (letters, digits, spaces, symbols, emojis) written inside quotes. You can use three kinds of quotes:

const single = 'Hello';
const double = "Hello";
const backtick = `Hello`;

console.log(single, double, backtick);

Single and double quotes work the same. Pick one style and stay with it. Backticks are special, and you will see why in a moment.

If your text contains the same quote you used outside, switch the quote type or escape it with a backslash \:

console.log("It's a sunny day");       // double quotes outside
console.log('She said "hello"');       // single quotes outside
console.log('It\'s a sunny day');      // escaped with \

Special characters

Code Meaning
\n New line
\t Tab
\\ A backslash
\' and \" A quote
console.log("Line 1\nLine 2");
console.log("Name:\tRiya");
console.log("C:\\Users\\Riya");

Output:

Line 1
Line 2
Name:	Riya
C:\Users\Riya

Length and indexing

Every string has a length property that tells you how many characters it contains. Spaces count too.

const word = "JavaScript";
console.log(word.length);       // 10
console.log("Hi there".length); // 8

Note that length has no brackets. It is a property, not a method.

Reading characters by index

Each character has a position called an index, and counting starts from 0, not 1.

 J  a  v  a  S  c  r  i  p  t
 0  1  2  3  4  5  6  7  8  9
const word = "JavaScript";

console.log(word[0]);          // "J"  (first character)
console.log(word[4]);          // "S"
console.log(word[word.length - 1]);   // "t"  (last character)
console.log(word[99]);         // undefined (no such position)

There are two other ways to read a character:

const word = "JavaScript";

console.log(word.charAt(1));   // "a"
console.log(word.at(-1));      // "t"  (negative number counts from the end)
console.log(word.at(-2));      // "p"

at(-1) is the easiest way to get the last character.

Strings are immutable

You cannot change a character inside an existing string. Strings are immutable, which means “unchangeable”.

let name = "Ravi";
name[0] = "S";          // does nothing (no error, but no change)
console.log(name);      // "Ravi"

To get a different string, you create a new one. This is important: every string method returns a new string and leaves the original untouched.

let name = "ravi";
name.toUpperCase();      // result is thrown away!
console.log(name);       // "ravi"

name = name.toUpperCase();   // save the result
console.log(name);           // "RAVI"

Template literals

Template literals use backticks and make building text much easier than joining pieces with +.

Putting values into text: ${ }

const name = "Riya";
const age = 20;

// The old way
console.log("My name is " + name + " and I am " + age + " years old.");

// The template literal way
console.log(`My name is ${name} and I am ${age} years old.`);

Anything inside ${ } is a JavaScript expression. It is calculated and put into the text:

const name = "Riya";
const age = 20;
const price = 250;
const quantity = 3;

console.log(`Total: ₹${price * quantity}`);          // "Total: ₹750"
console.log(`Is adult? ${age >= 18 ? "Yes" : "No"}`); // "Is adult? Yes"
console.log(`Shout: ${name.toUpperCase()}!`);          // "Shout: RIYA!"

Multi-line text

With quotes you need \n. With backticks, you just press Enter:

const message = `Dear Riya,

Your order has been shipped.

Thank you,
MyCodeNest`;

console.log(message);

This is great for emails, messages and HTML snippets.

Why template literals are better

  • No messy + signs and forgotten spaces.
  • No problems with mixing numbers and strings (they are all converted for you).
  • Multi-line text works naturally.

Tip: Use template literals whenever you build a sentence from variables.

String methods

A method is a function that belongs to a value. You call it with a dot and brackets, like text.toUpperCase(). Remember: they all return a new string.

Changing case

const text = "Hello World";

console.log(text.toUpperCase());   // "HELLO WORLD"
console.log(text.toLowerCase());   // "hello world"

A useful trick is to convert both texts to the same case before comparing:

const typed = "YES";
console.log(typed.toLowerCase() === "yes");   // true

Removing extra spaces

Users often type extra spaces by accident. trim() removes spaces (and tabs and new lines) from both ends:

const input = "   riya@example.com   ";

console.log(input.trim());        // "riya@example.com"
console.log(input.trimStart());   // "riya@example.com   "
console.log(input.trimEnd());     // "   riya@example.com"

It does not remove spaces in the middle of the text.

Searching inside a string

const sentence = "JavaScript is fun";

console.log(sentence.includes("fun"));        // true
console.log(sentence.startsWith("Java"));     // true
console.log(sentence.endsWith("fun"));        // true
console.log(sentence.indexOf("Script"));      // 4
console.log(sentence.indexOf("Python"));      // -1  (not found)
console.log(sentence.lastIndexOf("a"));       // 3  (position of the last "a")
  • includes(), startsWith() and endsWith() answer yes or no (true / false).
  • indexOf() gives the position of the first match, or -1 if there is none.
  • All searches are case-sensitive: "JavaScript".includes("script") is false.

Extracting a part: slice()

slice(start, end) returns the part of the text from start up to, but not including, end.

const word = "JavaScript";

console.log(word.slice(0, 4));    // "Java"   (index 0, 1, 2, 3)
console.log(word.slice(4));       // "Script" (from index 4 to the end)
console.log(word.slice(-6));      // "Script" (last 6 characters)
console.log(word.slice(1, -1));   // "avaScrip" (cut first and last)

Think of the numbers as markers placed before each character. slice(0, 4) cuts between marker 0 and marker 4.

There is also substring(start, end), which is similar but does not understand negative numbers, and an old substr() that is outdated. Use slice() and you will not need the others.

Replacing text

const text = "I like cats. Cats are great.";

console.log(text.replace("Cats", "Dogs"));      // only the FIRST match is replaced
console.log("a-b-a".replace("a", "X"));         // "X-b-a"
console.log("a-b-a".replaceAll("a", "X"));      // "X-b-X"  (all matches)

replace() changes only the first match, which surprises many beginners. Use replaceAll() to change every match.

Splitting into pieces and joining back

split() cuts a string into an array of pieces wherever it finds a separator:

console.log("apple,banana,mango".split(","));   // ["apple", "banana", "mango"]
console.log("hello world".split(" "));          // ["hello", "world"]
console.log("abc".split(""));                   // ["a", "b", "c"]

The reverse is join(), which belongs to arrays (you will study arrays soon):

const parts = ["apple", "banana", "mango"];
console.log(parts.join(" - "));   // "apple - banana - mango"

Padding and repeating

console.log("7".padStart(2, "0"));      // "07"
console.log("5".padStart(3, "0"));      // "005"
console.log("Name".padEnd(8, "."));     // "Name...."
console.log("ab".repeat(3));            // "ababab"

padStart() is perfect for clocks and invoice numbers, such as 07:05.

Comparing strings

console.log("apple" === "apple");   // true
console.log("apple" === "Apple");   // false (case matters)
console.log("a".localeCompare("b"));   // -1 ("a" comes first)
console.log("b".localeCompare("a"));   //  1
console.log("a".localeCompare("a"));   //  0 (same)

localeCompare() is mainly used for sorting names correctly, even with accents. Return values: negative (comes first), 0 (same), positive (comes later).

Method chaining

Since every method returns a string, you can call another method right away:

const messy = "   Learn JavaScript Fast!   ";
const clean = messy.trim().toLowerCase().replaceAll(" ", "-");

console.log(clean);   // "learn-javascript-fast!"

It reads from left to right: trim, then lower-case, then replace spaces.

Real-life use cases

1. Capitalise the first letter

const city = "mumbai";
const capitalised = city[0].toUpperCase() + city.slice(1);
console.log(capitalised);   // "Mumbai"

2. Build a URL-friendly slug from a blog title

const title = "  10 Tips for Learning JavaScript  ";
const slug = title.trim().toLowerCase().replaceAll(" ", "-");

console.log(slug);   // "10-tips-for-learning-javascript"

3. Mask a card or phone number

const card = "1234567890123456";
const masked = card.slice(-4).padStart(card.length, "*");

console.log(masked);   // "************3456"

4. Shorten long text

const text = "JavaScript makes web pages interactive and fun to build.";
const preview = text.slice(0, 25) + "...";

console.log(preview);   // "JavaScript makes web page..."

5. Count words

const sentence = "The quick brown fox";
console.log(sentence.trim().split(" ").length);   // 4

6. Format a time with leading zeros

const hours = 7;
const minutes = 5;

console.log(`${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`);   // "07:05"

7. Check a simple email and clean the input

const email = "  RIYA@Example.com ".trim().toLowerCase();

console.log(email);                // "riya@example.com"
console.log(email.includes("@"));  // true
console.log(email.endsWith(".com"));   // true

This is only a quick check. Real validation comes in the forms lesson.

8. Reverse a string and check for a palindrome

const word = "racecar";
const reversed = [...word].reverse().join("");

console.log(reversed);              // "racecar"
console.log(word === reversed);     // true (it is a palindrome)

[...word] turns the text into an array of characters. You will learn the spread syntax and reverse() later in the course. For now, just notice how string tools and array tools work together.

A note about emojis and special characters

JavaScript counts characters in a slightly unusual way. Some emojis take two positions:

console.log("😀".length);        // 2  (not 1!)
console.log([..."😀"].length);   // 1  (the spread version counts correctly)
console.log("héllo".length);     // 5

For normal English text this never matters. Just remember it if you build a character counter for a text box that has to support emojis.

Common mistakes

  • Forgetting that strings are immutable. name.toUpperCase(); alone does nothing. Save the result: name = name.toUpperCase();.
  • Writing text.length() with brackets. length is a property: use text.length.
  • Expecting replace() to change every match. It changes only the first. Use replaceAll().
  • Checking if (text.indexOf("a")). indexOf returns 0 when the match is at the start (falsy!) and -1 when missing (truthy!). Use includes() or compare with -1 explicitly.
  • Starting the index at 1. The first character is text[0].
  • Forgetting that searches are case-sensitive. Convert both sides to lowercase first.
  • Using + with numbers and strings. "Total: " + 5 + 5 gives "Total: 55". Use a template literal.
  • Using single quotes for backticks. 'Hello ${name}' prints the symbols literally. Only backticks (`) make ${ } work.
  • Forgetting trim() on user input. " yes" is not equal to "yes".

Practice

  1. Create a const with your full name. Print its length, its first letter, and its last letter using at(-1).
  2. Use a template literal to print: My name is ___ and I am learning JavaScript., with the name in a variable.
  3. Take the text " Hello, MyCodeNest! ". Remove the extra spaces, convert it to upper case, and print it.
  4. In the text "I love JavaScript. JavaScript is awesome.", replace every JavaScript with JS.
  5. Write code that takes "riya sharma" and prints "Riya Sharma". (Hint: split(" "), then slice the first letters, or do each word by hand.)
  6. Use padStart() to print the number 42 as "00042".
  7. Make a slug from the title "My First JavaScript Program!". Challenge: also remove the ! using replace().
  8. Predict the output before running: "hello".slice(1, 3), "hello".at(-2), "hello".indexOf("l"), "hello".lastIndexOf("l").

Recap

  • A string is text in single quotes, double quotes or backticks. Use \ to escape special characters, such as \n for a new line.
  • length gives the number of characters. Indexes start at 0. str[0] is the first character and str.at(-1) is the last.
  • Strings are immutable: methods return a new string, so save the result.
  • Template literals (backticks) allow ${ } expressions and multi-line text. Prefer them for building sentences.
  • Useful methods: toUpperCase(), toLowerCase(), trim(), includes(), startsWith(), endsWith(), indexOf(), slice(), replace(), replaceAll(), split(), padStart(), padEnd(), repeat().
  • Methods can be chained: text.trim().toLowerCase().
  • Searching is case-sensitive.
  • Next you will look at numbers and the Math object: parsing, NaN, rounding and random numbers.