Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 6 of 58

Strings

Create and combine text in JavaScript, use length, indexes and common string methods, escape special characters, and learn why strings never change.

13 minGetting startedUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCreate strings, read characters, search, slice and clean text with the common string methods, and explain why strings are immutable.

After this lesson you can build text values, pick them apart, search inside them, and tidy them up. Strings are everywhere on the web: names, messages, URLs and the text of the page itself.

Creating strings

A string is a run of characters wrapped in quotes. JavaScript accepts three kinds.

javascript
const a = "double quotes";
const b = 'single quotes';
const c = `backticks`;

Single and double quotes behave the same, so pick one and stay consistent. Backticks make template literals, which have their own lesson next.

Join strings with +:

javascript
const full = "Ada" + " " + "Lovelace";   // "Ada Lovelace"

Escaping

When your text contains the same quote that wraps it, or a special character, use a backslash.

javascript
console.log("it's");            // it's  (single quote is fine inside double quotes)
console.log('say "hi"');        // say "hi"
console.log("line1\nline2");    // two lines
console.log("tab\there");       // a tab in the middle
console.log("back\\slash");     // back\slash

The most useful escapes are \n for a new line, \t for a tab, \\ for a backslash, and \" or \' for a quote.

Length and characters

javascript
const s = "Hello, World";
console.log(s.length);    // 12
console.log(s[0]);        // H
console.log(s.at(-1));    // d

Positions are called indexes, and they start at 0. s[0] is the first character and s[s.length - 1] is the last. The at method accepts negative numbers to count from the end, which is shorter. Asking for an index that does not exist gives undefined.

A note on length: it counts UTF-16 code units, not what a person sees as one character. Plain letters count as 1 each, but an emoji such as the smiling face can count as 2. For everyday ASCII text you can ignore this. Do not rely on length for names in many languages or for emoji.

Strings cannot be changed

A string is immutable: you cannot alter one in place. Methods return a new string, and the original is left as it was.

javascript
let word = "cat";
word.toUpperCase();      // result thrown away
console.log(word);       // cat

word = word.toUpperCase();   // keep the result
console.log(word);       // CAT

Trying to write word[0] = "b" does nothing in a normal script, and throws an error in strict mode (which modules use). Create a new string instead.

Everyday methods

Here is a tour with the real output of each call, using s = "Hello, World".

javascript
s.toUpperCase()        // "HELLO, WORLD"
s.toLowerCase()        // "hello, world"
s.indexOf("o")         // 4   first match
s.lastIndexOf("o")     // 8   last match
s.indexOf("z")         // -1  not found
s.includes("World")    // true
s.startsWith("Hell")   // true
s.endsWith("d")        // true

Cutting pieces out

javascript
s.slice(0, 5)    // "Hello"   from index 0 up to, not including, 5
s.slice(-5)      // "World"   the last five
s.slice(7)       // "World"   from index 7 to the end

slice(start, end) is the one to learn. substring is similar, but treats negative numbers differently, so most people stick to slice.

Cleaning and reshaping

javascript
"  pad ".trim()            // "pad"     removes spaces at both ends
"a-b-c".split("-")         // [ 'a', 'b', 'c' ]
"a-b-c".replace("-", "+")  // "a+b-c"   only the first match
"a-b-c".replaceAll("-", "+") // "a+b+c"
"ab".repeat(3)             // "ababab"
"5".padStart(3, "0")       // "005"
"x".padEnd(3, ".")         // "x.."
["x", "y"].join("-")       // "x-y"    the reverse of split

padStart is handy for numbers such as 05 for a month or 007 for an ID. split("") turns a word into an array of its characters.

Comparing strings

Use === to check two strings are the same, and remember that case matters: "Cat" === "cat" is false. To compare ignoring case, lowercase both sides first. Comparison with < and > goes character by character: "10" < "9" is true, because "1" comes before "9". Compare numbers as numbers, not as text.

Try it

Edit the text and watch each method react.

html
<pre id="out"></pre>
<script>
  const input = "  Learn JavaScript, one step at a time  ";
  const clean = input.trim();
  const lines = [
    "trimmed:   " + clean,
    "length:    " + clean.length,
    "upper:     " + clean.toUpperCase(),
    "first 5:   " + clean.slice(0, 5),
    "has step?  " + clean.includes("step"),
    "words:     " + clean.split(" ").length,
    "swapped:   " + clean.replace("one", "every")
  ];
  document.getElementById("out").textContent = lines.join("\n");
</script>

Count words in a paragraph of your own text with the word counter, then check the answer against your own code. The case converter shows what toUpperCase and friends do on larger text.

Strings in real programs

Most of the text a program handles comes from outside: a name typed into a form, a title read from the page, a line of data from a server. That text is rarely tidy. People add spaces at the ends, type capitals in odd places, and paste text with extra separators. A very common routine is therefore to clean first and use afterwards: trim the spaces, lowercase the text for comparison, and only then search or split it. Doing the cleaning in one place, before anything else touches the value, keeps the rest of your code simple and avoids bugs where "Yes " and "yes" are treated as different answers.

Common mistakes

  • Forgetting to store the result. name.trim(); alone does nothing useful. Write name = name.trim();.
  • Off-by-one with indexes. The first character is index 0, and the last is length - 1.
  • Using replace and expecting every match. It changes only the first. Use replaceAll.
  • Comparing with different cases. Normalise with toLowerCase() before comparing.
  • Mixing up slice(start, end) ends. The end index is not included in the result.
  • Concatenating numbers and text. "Total: " + 5 + 3 gives "Total: 53". Calculate first, in brackets.

Exercise

  1. Store your full name in a string. Print its length, its upper-case version and its first name using slice and indexOf.
  2. Take " a,b,c,d ", trim it, split it on commas, and print how many pieces you get.
  3. Write code that turns the number 7 into "007". Hint: strings have a method for padding.

Next: Template literals.

Key points

  • A string is text in single quotes, double quotes or backticks, and counts characters from index 0.
  • Strings are immutable, so methods such as toUpperCase and replace return a new string and leave the original alone.
  • slice, indexOf, includes, startsWith, endsWith, trim, split and replaceAll cover most everyday text tasks.
  • Backslash escapes such as \n and \" let you include special characters.
  • length counts UTF-16 code units, so an emoji can count as 2.

Check yourself

1. After let s = "cat"; s.toUpperCase(); what is s?
2. What does "Hello, World".slice(-5) return?
3. What does "hello".indexOf("z") return?
4. Which method splits "a-b-c" into ["a", "b", "c"]?

Free tools for this lesson