Reading history

JavaScript Strings and String Methods (With Examples)

5 min read 1 views

Learn JavaScript strings: template literals, length, indexes, includes, indexOf, slice, trim, split, join, replaceAll, padStart and immutability.

A string is a piece of text: a name, an email address, a whole paragraph. Almost every program reads, checks, cleans or builds text, so JavaScript gives strings a large set of built-in methods. This lesson covers the ones you will use every day, from measuring and searching text to splitting it into parts and building new strings with template literals.

In this lesson you will learn

  • Three ways to write strings, and escape characters
  • Reading length and individual characters
  • Searching with includes, indexOf, startsWith
  • Extracting parts with slice
  • Cleaning and transforming with trim, split, replaceAll and more
  • Why strings are immutable

Writing Strings

const a = 'single quotes';
const b = "double quotes";
const c = `back quotes allow ${1 + 1} values and
several lines`;
const d = "She said \"hi\"\nand left.";   // \" is a quote, \n is a new line

Single and double quotes behave the same; pick one style and stick to it. Back quotes create template literals, which can hold ${...} expressions and line breaks. A backslash starts an escape sequence: \n (new line), \t (tab), \" and \\.

const course = "JavaScript Basics";

console.log(course.length);              // number of characters
console.log(course[0], course.at(-1));   // first and last character
console.log(course.toUpperCase());
console.log(course.toLowerCase());
console.log(course.indexOf("Basics"));   // position, or -1
console.log(course.includes("Script"));  // true / false
console.log(course.startsWith("Java"), course.endsWith("!"));
console.log(course.slice(0, 4));         // from 0 up to (not including) 4
console.log(course.slice(-6));           // last 6 characters

Output

17
J s
JAVASCRIPT BASICS
javascript basics
11
true
true false
Java
Basics
  • length is a property, not a method, so it has no parentheses. Spaces count as characters.
  • course[0] reads one character. at(-1) counts from the end, which is handy for the last character.
  • indexOf() returns the position where the text starts, or -1 if it is not found. includes(), startsWith() and endsWith() simply answer true or false.
  • All of these searches are case-sensitive. To search without caring about case, lower-case both sides first.
  • slice(start, end) copies the characters from start up to, but not including, end. A negative number counts from the end.

Cleaning, Splitting and Transforming

const raw = "   rahim@example.com  ";
const email = raw.trim();
console.log(`[${email}]`);

const csv = "Dhaka,Chattogram,Khulna,Sylhet";
const cities = csv.split(",");
console.log(cities, cities.length);
console.log(cities.join(" - "));

console.log("ha".repeat(3));
console.log("7".padStart(3, "0"));       // 007
console.log("2026-11-15".replaceAll("-", "/"));

const sentence = "the quick brown fox";
const titled = sentence
  .split(" ")
  .map((w) => w[0].toUpperCase() + w.slice(1))
  .join(" ");
console.log(titled);

// Strings are immutable: methods return new strings
let word = "cat";
word.toUpperCase();
console.log(word);          // still "cat"
word = word.toUpperCase();
console.log(word);          // now "CAT"

Output

[rahim@example.com]
[ 'Dhaka', 'Chattogram', 'Khulna', 'Sylhet' ] 4
Dhaka - Chattogram - Khulna - Sylhet
hahaha
007
2026/11/15
The Quick Brown Fox
cat
CAT
  • trim() removes spaces from both ends. Always trim text typed by users before checking it.
  • split(",") breaks a string into an array at each comma; join() does the reverse.
  • padStart(3, "0") fills the front up to a length, useful for invoice numbers and clock times.
  • replace() changes the first match only; replaceAll() changes every match.
  • The title-case example chains split, map and join to change each word.
  • Strings are immutable: methods never change the original string, they return a new one. Store the result if you want to keep it.

String Method Cheat Sheet

MethodExampleResult
toUpperCase()"hi".toUpperCase()"HI"
trim()" hi ".trim()"hi"
includes()"hello".includes("ell")true
slice()"hello".slice(1, 3)"el"
split()"a-b".split("-")["a", "b"]
replaceAll()"a.b.c".replaceAll(".", "/")"a/b/c"
padStart()"5".padStart(2, "0")"05"
repeat()"-".repeat(5)"-----"

Common Mistakes

  1. Writing length() with parentheses; it is a property.
  2. Expecting toUpperCase() to change the variable; assign the result.
  3. Testing if (str.indexOf("x")): a match at position 0 is falsy. Use includes().
  4. Comparing user input without trim() or a common case, so "Yes " does not equal "yes".

Practice Exercises

Exercise 1. Write isPalindrome(word) that returns true for words like “Level”, ignoring case.

Show answer
function isPalindrome(word) {
  const w = word.toLowerCase();
  return w === w.split("").reverse().join("");
}
console.log(isPalindrome("Level")); // true

Exercise 2. Count the words in " learn JavaScript today ".

Show answer
const text = "  learn   JavaScript today ";
const words = text.trim().split(/\s+/);
console.log(words.length); // 3

/\s+/ is a regular expression meaning “one or more spaces”, so repeated spaces count as one gap.

Frequently Asked Questions

How do I reverse a string in JavaScript?

Strings have no reverse method, so split into an array of characters, reverse it and join it back: str.split("").reverse().join("").

What is the difference between slice and substring?

Both copy part of a string. slice() accepts negative positions counted from the end; substring() treats negatives as 0. Most modern code uses slice().

Summary

  • Write strings with quotes or back quotes; back quotes allow ${} and line breaks.
  • length, indexes and at() read characters.
  • includes, indexOf and slice search and extract.
  • trim, split, join and replaceAll clean and reshape text.
  • String methods return new strings; the original never changes.

Next: JavaScript Numbers and Math.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *