Working with Strings Flashcards
What are string literals in JavaScript and how can they be used?
String literals in JavaScript are sequences of characters enclosed within single (' '
) or double (" "
) quotes. They can represent zero or more characters.
A string literal can be used directly, or any of the String object’s methods can be called on it. When a method is called on a string literal, JavaScript temporarily converts the string literal to a String object, performs the method, then discards the temporary String
object.
Here’s a simple example of string literals:
'foo' "bar" '1234' 'one line \n another line' "Joyo's cat"
“String literals” (developer.mozilla.org). Retrieved July 11, 2023.
What are the special characters in JavaScript and how are they represented?
- Null Byte:
"\0"
- Backspace:
"\b"
- Form Feed:
"\f"
- New Line:
"\n"
- Carriage Return:
"\r"
- Tab:
"\t"
- Vertical tab:
"\v"
- Apostrophe or single quote:
"'"
- Double quote:
"""
- Backslash character:
"\"
- Latin-1 character specified by up to three octal digits (0-377):
"\XXX"
- Latin-1 character specified by two hexadecimal digits (00-FF):
"\xXX"
- Unicode character specified by four hexadecimal digits:
"\uXXXX"
- Unicode code point escapes:
"\u{XXXXX}"
“String literals” (developer.mozilla.org). Retrieved July 12, 2023.
What are template literals aka template strings in JavaScript and how can they be used?
Template literals are a feature in JavaScript that provides an easy way to create complex strings. They are enclosed by the back-tick (`
) character and allow embedded expressions, multiline strings, and string formatting.
Here’s a basic example of template literal usage:
const name = 'John', time = 'today'; `Hello ${name}, how are you ${time}?` // "Hello John, how are you today?"
In this example, ${name}
and ${time}
are placeholders for the variables name and time. The expressions within the placeholders are evaluated and their results are inserted into the resulting string.
Template literals can also span across multiple lines without needing any special character:
`Hello ${name}, how are you ${time}?`
This would create a string that includes a line break. This is a major benefit over traditional strings which cannot span multiple lines without explicit newline characters (\n
).
“Template literals (Template strings) - JavaScript | MDN” (developer.mozilla.org). Retrieved July 11, 2023.
What are tagged templates in JavaScript and how are they used?
Tagged templates are an advanced form of template literals in JavaScript. They are a more concise and semantic way to invoke a function for processing a template literal.
In a tagged template, a function (the “tag”) is placed before the template literal and is called with the processed template literal. This allows the function to manipulate the output of the template literal in a customizable way.
The tag
function receives an array of string values as its first argument (the literal parts of the template) and the remaining arguments correspond to the processed substitution expressions.
Here’s an example of a tagged template:
const name = 'John', time = 'today'; function myTag(strings, personExp, timeExp) { const str0 = strings[0]; // "Hello " const str1 = strings[1]; // ", how are you " const timeStr = (timeExp === 'morning') ? 'this morning' : 'today'; return `${str0}${personExp}${str1}${timeStr}?`; } const output = myTag`Hello ${name}, how are you ${time}?`; console.log(output); // "Hello John, how are you today?"
In this example, myTag
is the tag function. It’s used to process the template literal Hello ${name}, how are you ${time}?
. The function receives the literal strings 'Hello '
and ', how are you '
in an array as its first argument, and the processed expressions for name
and time
as its next arguments. The function then processes these values to construct and return a customized string.
It’s worth noting that the function doesn’t need to return a string
. It can return any type of value based on the computations it does on the arguments. The first argument and its raw property are both frozen, so you can’t mutate them in any way. This ensures the stability of the array value and allows the tag function to cache results based on the identity of its first argument.
“Tagged templates” (developer.mozilla.org). Retrieved July 11, 2023.
What happens when a tagged template literal is chained in JavaScript?
While technically permitted by the syntax, untagged template literals are strings and will throw a TypeError
when chained. This happens because JavaScript tries to execute the first literal as a function, which fails because it’s a string. For example:
console.log(`Hello``World`); // This would throw a TypeError: "Hello" is not a function
“Tagged templates” (developer.mozilla.org). Retrieved July 11, 2023.
How can a tag function be used to create a template function in JavaScript?
A tag function can be used to create a function that generates a template based on passed values and keys. The tag function will return another function that when called, generates the final template. For example:
function template(strings, ...keys) { return (...values) => { const dict = values[values.length - 1] || {}; const result = [strings[0]]; keys.forEach((key, i) => { const value = Number.isInteger(key) ? values[key] : dict[key]; result.push(value, strings[i + 1]); }); return result.join(""); }; } const t1Closure = template`${0}${1}${0}!`; t1Closure("Y", "A"); // Outputs: "YAY!"
In this example, the template
function is a tag function that creates a closure for generating a template. This returned function can be later used with different values to create various templates.
“Tagged templates” (developer.mozilla.org). Retrieved July 11, 2023.
How does JavaScript ensure the stability of the array value passed as the first argument to a tag function?
To ensure the stability of the array value passed as the first argument to a tag function, JavaScript freezes the first argument and its raw property. This means they can’t be mutated in any way. Because of this, for any particular tagged template literal expression, the tag function will always be called with the exact same literal array, no matter how many times the literal is evaluated. This allows the tag to cache the result based on the identity of its first argument.
“Tagged templates” (developer.mozilla.org). Retrieved July 11, 2023.
What is the raw property of tagged templates?
The raw
property is available on the first argument to the tag function in a tagged template literal in JavaScript. It allows you to access the raw strings as they were entered, without processing escape sequences.
function tag(strings) { console.log(strings.raw[0]); } tag`string text line 1 \n string text line 2`; // Logs "string text line 1 \n string text line 2" , // including the two characters '\' and 'n'
“Raw strings” (developer.mozilla.org). Retrieved July 12, 2023.
How does the String.raw
tag method work in JavaScript?
The String.raw()
method in JavaScript is used to create raw strings, similar to default template functions and string concatenation. It creates a string exactly as entered, without processing any escape sequences.
const str = String.raw`Hi\n${2 + 3}!`; // "Hi\\n5!" str.length; // 6 Array.from(str).join(","); // "H,i,\\,n,5,!"
“Raw strings” (developer.mozilla.org). Retrieved July 12, 2023.
How can tagged template literals be used with formatters?
Tagged template literals can be useful with tools or formatters that give special treatment to literals tagged by a particular name. For example, if a formatter treats a literal’s content as HTML when tagged with a certain tag, you can use this tag to format your literal:
const html = (strings, ...values) => String.raw({ raw: strings }, ...values); // Some formatters will format this literal's content as HTML const doc = html`<!doctype html> <html lang="en-US"> <head> <title>Hello</title> </head> <body> <h1>Hello world!</h1> </body> </html>`;
“Raw strings” (developer.mozilla.org). Retrieved July 12, 2023.
How do you escape characters in JavaScript?
- You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:
const quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
- To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, you can use:
const home = "c:\\temp";
- You can escape line breaks by preceding them with a backslash. The backslash and line break are both removed from the value of the string. For example:
const str = "this string \ is broken \ across multiple \ lines.";
“String literals” (developer.mozilla.org). Retrieved July 12, 2023.
How do tagged templates handle escape sequences?
In normal template literals, all the escape sequences in string literals are allowed, and any non-well-formed escape sequence is a syntax error. However, in tagged templates, they have access to the raw literals where escape sequences are preserved as-is, allowing the embedding of languages where other escape sequences are common. Therefore, the syntax restriction of well-formed escape sequences is removed from tagged templates.
Here’s an example:
function latex(str) { return { cooked: str[0], raw: str.raw[0] }; } latex`\unicode`; // { cooked: undefined, raw: "\\unicode" }
This feature of tagged templates allows for more flexibility when working with escape sequences.
“Tagged templates and escape sequences” (developer.mozilla.org). Retrieved July 13, 2023.
How can you find the length of a string?
Using the length
property.
const browserType = "mozilla"; browserType.length; // 7
“String: length - JavaScript | MDN” (developer.mozilla.org). Retrieved November 3, 2023.
How can you retrieve an specific string character?
You can return any character inside a string by using square bracket notation — this means you include square brackets ([]
) on the end of your variable name. Inside the square brackets, you include the number of the character you want to return, so for example to retrieve the first letter you’d do this:
const browserType = "mozilla"; browserType[0]; // 'm'
Remember: computers count from 0, not 1!
To retrieve the last character of any string, we could use the following line, combining this technique with the length
property we looked at above:
browserType[browserType.length - 1] // 'a'
“Retrieving a specific string character” (developer.mozilla.org). Retrieved November 3, 2023.
How can you test if a string contains a substring?
Using the includes()
method, which takes a single parameter — the substring you want to search for.
It returns true
if the string contains the substring, and false
otherwise.
const browserType = "mozilla"; if (browserType.includes("zilla")) { console.log("Found zilla!"); } else { console.log("No zilla here!"); }
“Testing if a string contains a substring” (developer.mozilla.org). Retrieved November 3, 2023.