Strings
- In JavaScript, there are 3 types of quotes.
- Double quotes:
"Hello"
. - Single quotes:
'Hello'
. - Backticks:
`Hello`
.
- Double quotes:
- Double and single quotes are “simple” quotes. There’s practically no difference between them in JavaScript.
- Backticks are “extended functionality” quotes. They have many uses which we will soon be learning.
- Template literals are literals delimited with backtick (
`
) characters. -
Escaping characters in string
- The following will error, as it confuses the browser as to where the string ends:
const bigmouth = 'I've got no right to take my place…';
- To fix this, we use a backslash just before the character:
const bigmouth = 'I\'ve got no right to take my place…'; console.log(bigmouth); // I've got no right to take my place...
- See Escape sequences for more details.
- The following will error, as it confuses the browser as to where the string ends:
-
Concatenating strings
- To join together strings in JavaScript you can use a different type of string, called a template literal.
- A template literal looks just like a normal string, but instead of using single or double quote marks, we use backtick characters.
- This can work just like a normal string, except you can include variables in it, wrapped inside
${ }
characters, and the variable's value will be inserted into the result:const name = "Chris"; const greeting = `Hello, ${name}`; console.log(greeting); // "Hello, Chris"
- You can use the same technique to join together two variables:
const one = "Hello, "; const two = "how are you?"; const joined = `${one}${two}`; console.log(joined); // "Hello, how are you?"
-
Concatenation using "+"
-
const greeting = "Hello"; const name = "Chris"; console.log(greeting + ", " + name); // "Hello, Chris"
-
-
Concatenation strings and numbers
-
const name = "Front "; const number = 242; console.log(`${name}${number}`); // "Front 242"
- If you have a numeric variable that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs:
Number()
- The
Number()
function converts anything passed to it into a number, if it can.const myString = "123"; const myNum = Number(myString);
- The
toString()
const myNum2 = 123; const myString2 = myNum2.toString();
-
-
Multiline strings
- Template literals respect the line breaks in the source code, so you can write strings that span multiple lines like this:
const output = `I like the song. I gave it a score of 90%.`; console.log(output); /* I like the song. I gave it a score of 90%. */
- To break the line, you can also use
\n
instead.const output = "I like the song.\nI gave it a score of 90%."; console.log(output); /* I like the song. I gave it a score of 90%. */
- Template literals respect the line breaks in the source code, so you can write strings that span multiple lines like this:
-
JavaScript String Methods