Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 156 Β· Data Types

Strings

Learn JavaScript strings - single, double and backtick quotes, escape sequences, length and indexing, why strings are immutable, joining text and comparing strings.

A string is a piece of text: a name, a message, an email address, a whole paragraph, or even an empty piece of text with no characters at all. Strings are probably the type you'll use most, because nearly everything a program shows to people is text.

In this lesson you'll learn how to write strings, how to include special characters such as quotes and line breaks, how to read individual characters, why a string can never be changed in place, and how comparing strings works (including a few results that look wrong until you know the rule). The next lesson covers the many built-in methods for searching and transforming text.

Three kinds of quotes

You create a string by wrapping text in quotes. JavaScript accepts three kinds:

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

Single and double quotes behave identically. Pick one and use it consistently; this course uses double quotes, and many teams let a formatter decide for them. The quote that starts a string must also end it.

Backticks create template literals, which have two extra powers: they can span several lines, and they can embed values with ${...}:

JavaScript
const name = "Sam";
const items = 3;
const message = `Hi ${name}, you have ${items} items in your cart.`;

Template literals are so useful that they have their own lesson, Template Literals. For now, just recognize them.

Escape sequences

What if your text contains the same quote you used to wrap it? The string would end too early. You can either switch quote styles or escape the character with a backslash \, which tells JavaScript "the next character is part of the text":

JS Quotes and escapes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The escape sequences you'll use most:

Sequence Meaning
\n New line
\t Tab
\\ A backslash
\" and \' A quote character
\` A backtick (inside template literals)
\u00e9, \u{1F600} A Unicode character by its code

A common Windows trap: file paths like "C:\new" contain \n, which becomes a line break. Escape each backslash ("C:\\new") or use forward slashes, which most tools accept.

Length and individual characters

Every string has a length property that tells you how many characters it contains. You can read a single character by its index, its position counted from zero, using square brackets:

JS Length and indexes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because counting starts at zero, the last character is at index length - 1, not length. Reading past the end doesn't throw an error; it just gives undefined. The at() method, added in ES2022 and supported in all modern browsers, makes "last character" easy: negative numbers count from the end.

The for...of loop visits each character in turn. You'll learn loops properly in for...of and for...in.

A note on emoji and length

length counts UTF-16 code units, not the characters you see. Most characters are one unit, but emoji and some rarer symbols take two, so "πŸ˜€".length is 2. If you need the number of visible characters, spread the string into an array first:

JavaScript
console.log("πŸ˜€".length);         // 2
console.log([..."πŸ˜€"].length);    // 1

Even that isn't perfect for emoji built from several parts, such as family or flag emoji. For most everyday text, including accented letters like Γ©, length works exactly as you'd expect.

Strings are immutable

Strings are primitives, and primitives can't be changed. You can read word[0], but you can't assign to it: in normal scripts the assignment is silently ignored, and in strict mode it throws a TypeError.

JS You can't change a string in place

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Every string method returns a new string and leaves the original alone. So if you want to keep the result, store it in a variable, or reassign a let variable as above. Forgetting this is a classic beginner bug: name.trim(); on its own line does nothing useful, while name = name.trim(); works.

Joining strings

The + operator joins (concatenates) strings, and += appends to a variable:

JavaScript
const first = "Grace";
const last = "Hopper";
const full = first + " " + last;   // "Grace Hopper"

let log = "Started";
log += ", loaded";
log += ", done";                   // "Started, loaded, done"

When you join a string with a number, the number is converted to text: "Room " + 101 gives "Room 101". But be careful with the order of operations: "Total: " + 2 + 3 gives "Total: 23", because the first + produces a string and the second joins "3" to it. Use parentheses, "Total: " + (2 + 3), or a template literal to do the math first. Arithmetic Operators explains the rules in detail.

Comparing strings

Use === to check whether two strings are exactly the same. The comparison is case-sensitive and counts every space:

JS Comparing strings

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The < and > operators compare strings character by character, by their character codes. All uppercase letters have lower codes than all lowercase letters, so "Zebra" sorts before "apple", and accented letters come after z. Digits are compared as characters too, so the string "10" is "less than" "9". Convert numeric strings with Number() before comparing them.

For sorting words the way people expect, use localeCompare(). It returns a negative number if the first string comes before the second, a positive number if it comes after, and 0 if they're equivalent, following the alphabet rules of a language. You'll use it in Sorting Arrays, and Formatting with Intl shows how to control it further.

Converting other values to strings

To turn any value into a string, use String(value). Numbers and booleans also have a toString() method:

JavaScript
String(42);          // "42"
String(true);        // "true"
String(null);        // "null"
(255).toString(16);  // "ff"

String() is the safest choice because it also works on null and undefined, where calling .toString() would throw a TypeError.

String recipes

Because strings are immutable, every "change" builds a new string. These recipes show the usual patterns. They use a few methods and regular expressions that later lessons explain in full (String Methods and Regular Expressions), so treat them as ready-made tools for now and come back when you want to understand every character.

Case conversions and slugs

A slug is the lowercase, hyphenated part of a URL such as my-first-post. Converting between camelCase, kebab-case and snake_case follows the same idea: split the text into words, then join the words in the new style.

JS Slugs and naming styles

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Counting, inserting and masking

split() and join() give a short way to count or replace without a regular expression, and slice() lets you cut a string in two at any index and glue something in between.

JS Count, insert, truncate, mask

Press Run (or Ctrl + Enter) to see the console output here.

No output.

padStart() pads on the left until the string reaches the requested length. Padding the last few characters out to the full length is the shortest way to mask a card or phone number for display. (Masking is only for display: never rely on it to protect secrets that are still sent to the browser.)

Cleaning text and abbreviating numbers

JS Strip characters and shorten numbers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Code points and a simple hash

Every String is a sequence of 16-bit units, so charCodeAt() can return half of an emoji. codePointAt() and String.fromCodePoint() work with whole characters. A tiny hash turns any string into a number, which is handy for picking a stable color or a bucket for a name. It is not secure; use crypto.subtle.digest when you need a real cryptographic hash.

JS codePointAt and a string hash

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Recipes like these are also great practice problems. Try writing countVowels with a loop instead of a regex, or extend slugify to keep numbers but turn & into the word and before slugifying.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. Which string is written correctly?

    Double quotes can contain an apostrophe freely. The first ends at the apostrophe, the third mixes opening and closing quotes, and the last has no quotes.
  2. 2. With const city = "Paris";, what is city[city.length - 1]?

    Indexes start at 0, so the last character is at length - 1, which is index 4, the letter s. city.at(-1) gives the same result.
  3. 3. After let tag = "div"; tag.toUpperCase();, what is tag?

    Strings are immutable. toUpperCase() returns a new string, which was thrown away. Write tag = tag.toUpperCase(); to keep it.
  4. 4. Why is "Zebra" < "apple" true?

    The < operator compares character codes, and every uppercase letter comes before every lowercase letter. Use localeCompare() for human alphabetical order.
  5. 5. What does "\n" represent inside a string?

    \n is an escape sequence for a line break. To get a literal backslash, write \\.

Summary

  • Strings are text in single quotes, double quotes or backticks. Backticks create template literals with ${...} and multi-line support.
  • Escape special characters with a backslash: \n, \t, \\, \", \' and \u{...}.
  • length gives the number of UTF-16 units. Read characters with [index] (from 0) or at(), which accepts negative indexes.
  • Strings are immutable: methods return new strings, so store the result.
  • + and += join strings; numbers are converted to text.
  • === compares exactly and is case-sensitive. < and > compare character codes; use localeCompare() for alphabetical order.

Next: String Methods β€” searching, slicing and transforming text.