A string is a piece of text: a name, a sentence, a password, a single letter, or even nothing at all. Formally, a string is zero or more characters written inside quotes. Strings are one of the types you will use most, because nearly everything a user sees or types is text.
You can use double quotes, single quotes, or backticks:
let a = "Volvo XC60"; // double quotes
let b = 'Volvo XC60'; // single quotes: exactly the same string
let c = `Volvo XC60`; // backticks: a template string (next lesson)
let empty = ""; // zero characters: still a string
Single and double quotes work identically; there is no difference at all between them. Pick one style and use it consistently. Backticks have extra powers, covered in JS String Templates.
A string can contain quotes, as long as they do not match the quotes around it:
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
let answer4 = `He's often called "Johnny"`; // backticks allow both
Matching quotes are a problem, because JavaScript thinks the string has ended:
let text = "We are the so-called "Vikings" from the north.";
JavaScript reads "We are the so-called " as a complete string, then finds the word Vikings sitting loose in the code, which makes no sense to it. The whole script fails to run.
To put a matching quote inside a string, put a backslash \ in front of it. The backslash is the escape character: it tells JavaScript "the next character is part of the text, not code":
let text1 = "We are the so-called \"Vikings\" from the north.";
let text2 = 'It\'s alright.';
let text3 = "The character \\ is called backslash.";
console.log(text1);
console.log(text3);
Notice that to get one backslash into the string, you write two. A single \ would try to escape the next character.
| Code | Result | Use it? |
|---|---|---|
| \" | Double quote | Often |
| \' | Single quote | Often |
| \\ | Backslash | Often (file paths) |
| \n | New line | Often |
| \t | Horizontal tab | Sometimes |
| \r | Carriage return | Rarely |
| \b | Backspace | Rarely |
| \f | Form feed | Rarely |
| \v | Vertical tab | Rarely |
The last four were designed to control typewriters, teletypes, and fax machines. You will almost never need them, and they do nothing useful in a web page.
console.log("Line one\nLine two");
console.log("Name:\tAlex");
console.log("C:\\Users\\alex");
\n makes a new line in the console and in text boxes. But when you put a string into a web page's HTML, HTML ignores line breaks, and the text all runs together on one line. On a page you need an HTML <br> tag instead.
Every string has a length property: the number of characters it holds. Spaces and punctuation count:
console.log("ABCDEFGHIJKLMNOPQRSTUVWXYZ".length);
console.log("Hi there!".length);
console.log("".length);
Note: length is a property, not a method, so it has no parentheses. "hi".length() is a TypeError.
Each character has a position number, called its index, starting at 0. Use square brackets to read one:
let word = "Code";
// C=0 o=1 d=2 e=3
console.log(word[0]);
console.log(word[3]);
console.log(word[word.length - 1]); // the last character
console.log(word[10]); // past the end
Because the first index is 0, the last index is always length - 1. This is the same rule as arrays.
The + operator joins strings together. This is called concatenation:
let first = "Ada";
let last = "Lovelace";
let full = first + " " + last;
console.log(full);
You cannot press Enter in the middle of a quoted string; that is a SyntaxError. To split a long string across lines in your code, break it into pieces and join them with + at the end of each line:
let message = "This is a very long message that would " +
"run off the edge of the editor if it were " +
"all on one line.";
It is still one string. Backtick strings, in the next lesson, can span lines directly.
Strings are immutable: once created, their characters cannot be edited in place. You make a new string instead.
let name = "cat";
name[0] = "b"; // silently ignored
console.log(name);
name = "b" + name.slice(1); // build a new string from "b" + "at"
console.log(name);
(slice(1) copies everything from index 1 onward; JS String Methods covers it.) Normally name[0] = "b" fails without any error. In strict mode it throws TypeError: Cannot assign to read only property '0' of string 'cat', which is much more helpful.
console.log(5 + 5);
console.log("5" + "5");
console.log(typeof "5");
Number() (covered in JS Number Methods).
Normally strings are simple primitive values: let x = "John";. But, like booleans, they can also be created as objects with new. Never do this; it slows code down and breaks comparisons:
let x = "John";
let y = new String("John");
console.log(typeof y);
console.log(x == y); // loose: converts y, then compares
console.log(x === y); // strict: string vs object
let a = new String("John");
let b = new String("John");
console.log(a == b); // two objects: never equal
That last one is the killer: two String objects holding identical text are not equal, even with ==, because comparing two objects checks whether they are the same object, not whether they hold the same text.
Which of these is not a valid string?
"It's here"'It\'s here''It's here'`It's here`It. B fixes it with an escape; A and D use different outer quotes.What does this log?
let word = "planet";
console.log(word.length, word[1], word[word.length - 1]);
6 l t. Six characters; index 1 is the second character (l); the last index is 5, which is t.How do you write a string containing a single backslash, like C:\temp?
"C:\temp""C:\\temp""C:/temp""C:\'temp"\\ produces one backslash. A is a trap: \t is a tab, so it gives C: followed by a tab and emp.fullName and log its length, then its first and last characters\nnew String("hi") === new String("hi") and explain the result