JavaScript Strings

A string in JavaScript is a sequence of characters used to store and work with text.

What is a String?

Strings hold text: a name, a sentence, a URL, or even a single character. You create a string by wrapping characters in quotes. JavaScript accepts three kinds of quotes, and all of them produce the same type of value — a primitive string.

  • Double quotes: "Hello world"
  • Single quotes: 'Hello world'
  • Backticks (template literals): `Hello world`
  • The quotes you open with must match the quotes you close with.

Creating strings

<!DOCTYPE html>
<html>
<body>

<h2>Creating strings</h2>

<script>
let greeting = "Hello";
let name = 'Ada';
let phrase = `Learning JavaScript`;

console.log(greeting); // Hello
console.log(name);     // Ada
console.log(phrase);   // Learning JavaScript
</script>

</body>
</html>

When your text itself contains a quote character, you can either use a different quote style on the outside, or escape the inner quote with a backslash. The backslash tells JavaScript to treat the next character as plain text rather than as the end of the string.

Quotes inside strings and escaping

<!DOCTYPE html>
<html>
<body>

<h2>Quotes inside strings and escaping</h2>

<script>
let a = "It's a sunny day";        // single quote inside double quotes
let b = 'She said "hi" to me';      // double quote inside single quotes
let c = 'It\'s escaped';            // backslash escapes the quote
let d = "Line one\nLine two";       // \n adds a new line

console.log(c); // It's escaped
</script>

</body>
</html>
Note: Strings are zero-indexed. The first character is at position 0, the second at position 1, and so on. The length of a string is available through its length property.

You can read the number of characters in a string with .length, and reach any single character by its index using bracket notation or the charAt() method.

Length and accessing characters

<!DOCTYPE html>
<html>
<body>

<h2>Length and accessing characters</h2>

<script>
let word = "JavaScript";

console.log(word.length);   // 10
console.log(word[0]);       // J
console.log(word[4]);       // S
console.log(word.charAt(1)); // a
</script>

</body>
</html>
Note: Strings are immutable. Methods that appear to change a string actually return a brand new string and leave the original untouched, so word[0] = 'X' has no effect.
Property / AccessDescriptionExample result
lengthNumber of characters in the string"abc".length → 3
[index]Character at a given position"abc"[0] → "a"
charAt(index)Character at a position (method form)"abc".charAt(2) → "c"
\nEscape sequence for a new lineadds a line break
\"Escape sequence for a literal quoteprints a quote character

Exercise: JavaScript Strings

Can you change a single character of a string in place?