Skip to main content

JavaScript Strings

JavaScript Strings

Written by Published

A JavaScript string holds text, written inside quotes.

Single and double quotes do exactly the same job.

Backticks do something extra, which the next lesson covers.

Example

Example

javascript

const name = "Ada Lovelace";

console.log(name.length);

The output is 12, counting the space.

What is a String?

A string is a sequence of characters.

length tells you how many characters it holds.

Each character has an index, starting at 0.

Syntax

Syntax

javascript

const text = "hello";
const other = 'hello';

Pick one quote style and stay with it.

Quotes Inside Quotes

Use the other kind of quote, so you do not have to escape anything.

Example

Example

javascript

const a = "It's fine";
const b = 'She said "hello"';

console.log(a);
console.log(b);

An apostrophe inside single quotes would end the string early.

Reading a Character

Square brackets work, and at also accepts negative numbers.

Example

Example

javascript

const text = "hello";

console.log(text[0]);
console.log(text.at(-1));

The output is h then o.

Counting Characters

length is a property, not a method, so it has no brackets.

Example

Example

javascript

const text = "hello world";

console.log(text.length);
console.log(text[text.length - 1]);

The last index is always length - 1.

Strings Cannot Be Changed

Assigning to a position does nothing at all.

Every string method returns a new string instead.

Example

Example

javascript

const text = "hello";

text[0] = "H";

console.log(text);

The output is still hello.

Empty and Whitespace

An empty string has a length of 0; a space is a real character.

Example

Example

javascript

console.log("".length);
console.log(" ".length);
console.log("   ".trim().length);

The output is 0, 1, 0.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Strings</title>
</head>
<body>

  <h1>JavaScript Strings</h1>

  <p id="out"></p>

  <script>
    const name = "Ada Lovelace";

    document.getElementById("out").innerHTML =
      "Text: " + name +
      "<br>Length: " + name.length +
      "<br>First letter: " + name[0] +
      "<br>Last letter: " + name.at(-1);
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try your own name:

Change the text and watch the length update.

Important Points

  • A string holds text inside quotes.
  • Single and double quotes behave the same.
  • length counts the characters.
  • Characters are read by index, starting at 0.
  • Strings cannot be changed in place.

Conclusion

Strings are in almost every program you will write.

The one rule to remember is that they never change; methods return new ones.

The rest of this section covers what those methods do.