Working with Strings Flashcards

1
Q

What are string literals in JavaScript and how can they be used?

A

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"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the special characters in JavaScript and how are they represented?

A
  • 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}"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are template literals aka template strings in JavaScript and how can they be used?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are tagged templates in JavaScript and how are they used?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What happens when a tagged template literal is chained in JavaScript?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can a tag function be used to create a template function in JavaScript?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How does JavaScript ensure the stability of the array value passed as the first argument to a tag function?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the raw property of tagged templates?

A

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'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does the String.raw tag method work in JavaScript?

A

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,!"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can tagged template literals be used with formatters?

A

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>`;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you escape characters in JavaScript?

A
  • 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.";
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do tagged templates handle escape sequences?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can you find the length of a string?

A

Using the length property.

const browserType = "mozilla";
browserType.length; // 7
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can you retrieve an specific string character?

A

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'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How can you test if a string contains a substring?

A

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!");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can you find the possition of a substring in a string?

A

You can find the position of a substring inside a larger string using the indexOf() method. This method takes two parameters – the substring that you want to search for, and an optional parameter that specifies the starting point of the search.

If the string contains the substring, indexOf() returns the index of the first occurrence of the substring. If the string does not contain the substring, indexOf() returns -1.

const tagline = "MDN - Resources for developers, by developers";
console.log(tagline.indexOf("developers")); // 20

So now that you know how to find the first occurrence of a substring, how do you go about finding subsequent occurrences? You can do that by passing in a value that’s greater than the index of the previous occurrence as the second parameter to the method.

const firstOccurrence = tagline.indexOf("developers");
const secondOccurrence = tagline.indexOf("developers", firstOccurrence + 1);

console.log(firstOccurrence); // 20
console.log(secondOccurrence); // 35

Here we’re telling the method to search for the substring "developers" starting at index 21 (firstOccurrence + 1), and it returns the index 35.

17
Q

How can you extract a substring of a string?

A

You can extract a substring from a string using the String.prototype.slice() method or the String.prototype.substring() method. You pass it:

  1. The index at which to start extracting
  2. Optionally, you can pass the index at which to stop extracting. This is exclusive, meaning that the character at this index is not included in the extracted substring. If omitted it will extract until the end of the string.

For example:

const browserType = "mozilla";
console.log(browserType.slice(1, 4)); // "ozi"
18
Q

What are the differences between String.prototype.substring() and String.prototype.slice()?

A

The substring() and slice() methods are almost identical, but there are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.

  • The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The slice() method returns an empty string if this is the case.
const text = "Mozilla";
console.log(text.substring(5, 2)); // "zil"
console.log(text.slice(5, 2)); // ""
  • If either or both of the arguments are negative or NaN, the substring() method treats them as if they were 0.
console.log(text.substring(-5, 2)); // "Mo"
console.log(text.substring(-5, -2)); // ""
  • slice() also treats NaN arguments as 0, but when it is given negative values it counts backwards from the end of the string to find the indexes.
console.log(text.slice(-5, 2)); // ""
console.log(text.slice(-5, -2)); // "zil"
19
Q

How can you update the casing of a string?

A

The string methods toLowerCase() and toUpperCase() take a string and convert all the characters to lower- or uppercase, respectively. This can be useful for example if you want to normalize all user-entered data before storing it in a database.

Let’s try entering the following lines to see what happens:

const radData = "My NaMe Is MuD";
console.log(radData.toLowerCase());
console.log(radData.toUpperCase());
20
Q

How can you update parts of a string?

A

You can replace one substring inside a string with another substring using the replace() method.

In this example, we’re providing two parameters — the string we want to replace, and the string we want to replace it with:

const browserType = "mozilla";
const updated = browserType.replace("moz", "van");

console.log(updated); // "vanilla"
console.log(browserType); // "mozilla"

Note that replace(), like many string methods, doesn’t change the string it was called on, but returns a new string.

21
Q

How can you trim the white spaces at the begining and end of a string?

A

Using the trim() method.

For example:

const greeting = '   Hello world!   ';

console.log(greeting);
// Expected output: "   Hello world!   ";

console.log(greeting.trim());
// Expected output: "Hello world!";