String Data Type
Data Types: Strings
What is a string in JavaScript, and how is it represented in code?
View Answer:
Sure, here are a few examples of creating and using strings in JavaScript.
1. Creating Strings:
let str1 = 'Hello, JavaScript!'; // single quotes
let str2 = "Hello, JavaScript!"; // double quotes
let str3 = `Hello, ${name}!`; // template literal
2. Concatenating Strings:
let hello = 'Hello, ';
let javascript = 'JavaScript!';
let helloJavaScrpt = hello + javascript; // 'Hello, JavaScript!'
3. Using Template Literals:
let name = 'JavaScript';
let greeting = `Hello, ${name}!`; // 'Hello, JavaScript!'
4. String Methods:
let text = 'The quick brown fox jumps over the lazy dog.';
let textLength = text.length; // 43
let textInUpperCase = text.toUpperCase(); // 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.'
let wordPosition = text.indexOf('fox'); // 16
let replacedText = text.replace('dog', 'cat'); // 'The quick brown fox jumps over the lazy cat.'
In these examples, we are performing various operations on strings such as concatenation, conversion to uppercase, finding the position of a word in the string, and replacing a word in the string with another word. These are just a few of the many methods available for working with strings in JavaScript.
In JavaScript, is there a data type for a single character?
View Answer:
let char = 'a';
If you want to access a specific character in a string, you can use bracket notation or the charAt
method, like so:
let str = 'Hello';
console.log(str[1]); // "e"
console.log(str.charAt(1)); // "e"
These both access the character at index 1 (zero-based indexing) of the string 'Hello', which is the character 'e'.
What type of internal character encoding does JavaScript always use?
View Answer:
What type of string encoding does JavaScript use?
View Answer:
What are the three types of quotes used to enclose strings in JavaScript?
View Answer:
let single = 'single-quoted';
let double = 'double-quoted';
let backticks = `backticks and ${single}`;
console.log(backticks) // logs "backticks and single-quoted"
Can you explain the difference between single, double, and backticks?
View Answer:
function sum(a, b) {
return a + b;
}
console.log(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.
// spanning multiple lines
let guestList = `Guests:
* John
* Pete
* Mary
`;
console.log(guestList); // a list of guests, multiple lines
// this will result in an error with single or double quotes
let guestList = "Guests: // Error: Unexpected token ILLEGAL
* John";
Can single or double quotes be used to generate a multiline string?
View Answer:
let guestList = 'Guests:\n * John\n * Pete\n * Mary';
console.log(guestList); // a multiline list of guests
//////////////////////////////////////////////
// Example, these two lines are equal, just written differently:
let str1 = 'Hello\nWorld'; // two lines using a "newline symbol"
// two lines using a normal newline and backticks
let str2 = `Hello
World`;
console.log(str1 == str2); // true
What is the one thing that all special characters in JavaScript have in common?
View Answer:
console.log("I'm the Walrus!"); // I'm the Walrus!
// Ways to avoid the need to prepend the inner quote
console.log(`I'm the Walrus!`); // I'm the Walrus!
// Example if you need to show the backslash...
console.log(`The backslash: \\`); // The backslash: \
Is string length a property or function in JavaScript?
View Answer:
console.log(`Hello`.length); // 5
When accessing string characters at a specific position. What is the difference between accessing it with square brackets and the charAt() method?
View Answer:
let str = `Hello`;
console.log(str[1000]); // undefined
console.log(str.charAt(1000)); // '' (an empty string)
// We can also iterate over characters using for..of:
for (let char of 'Hello') {
console.log(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc)
}
Are strings mutable or immutable in JavaScript, and why?
View Answer:
// Using a string method doesn't mutate the string
let bar = 'baz';
console.log(bar); // baz
bar.toUpperCase();
console.log(bar); // baz
// Using an array method mutates the array
let foo = [];
console.log(foo); // []
foo.push('plugh');
console.log(foo); // ["plugh"]
// Assignment gives the primitive a new (not a mutated) value
bar = bar.toUpperCase(); // BAZ
What two methods can we use to change the case of a string?
View Answer:
console.log('Interface'.toUpperCase()); // INTERFACE
console.log('Interface'.toLowerCase()); // interface
// Or, if we want a single character lower cased
console.log('Interface'[0].toLowerCase()); // 'i'
Can you explain the function of the string indexOf() method?
View Answer:
let str = 'Widget with id';
console.log(str.indexOf('Widget')); // 0, because 'Widget' is found at the beginning
console.log(str.indexOf('widget')); // -1, not found, the search is case-sensitive
console.log(str.indexOf('id')); // 1, "id" is found at position 1 (..idget with id)
// Running indexOf in a LOOP
let str = 'As sly as a fox, as strong as an ox';
let target = 'as'; // let's look for it
let pos = 0;
while (true) {
let foundPos = str.indexOf(target, pos);
if (foundPos == -1) break;
console.log(`Found at ${foundPos}`);
pos = foundPos + 1; // continue the search from the next position
}
The indexOf()
method cannot take powerful search values (regular expressions) as the search method. We should note that the indexOf search is case-sensitive.
What is the difference between the string indexOf and lastIndexOf methods?
View Answer:
const paragraph =
'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const searchTerm = 'dog';
console.log(
`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(
searchTerm
)}`
);
// expected output: "The index of the first "dog" from the end is 52"
What is the difference between the string indexOf and search methods?
View Answer:
Here are examples of indexOf
and search
methods in JavaScript.
let str = 'Hello, JavaScript!';
let index = str.indexOf('JavaScript'); // returns 7
console.log(index);
let regexSearch = str.search(/JavaScript/); // returns 7
console.log(regexSearch);
Both indexOf
and search
found the substring 'JavaScript' at the index 7 in the string 'Hello, JavaScript!'. The difference is, search
used a regular expression (/JavaScript/).
What is the potential negative outcome when using the indexOf() method in an if-statement?
View Answer:
let str = 'Widget with id';
if (str.indexOf('Widget')) {
console.log('We found it'); // doesn't work!
}
// Quick Fix: Use a -1 check
let str = 'Widget with id';
if (str.indexOf('Widget') != -1) {
console.log('We found it'); // works now!
}
What is a common trick to convert a number to a 32-bit integer?
View Answer:
console.log(~2); // -3, the same as -(2+1)
console.log(~1); // -2, the same as -(1+1)
console.log(~0); // -1, the same as -(0+1)
console.log(~-1); // 0, the same as -(-1+1)
Can you use the Bitwise (~) Not to ensure that a call on the indexOf method acts in the intended fashion in an if statement?
View Answer:
let str = 'Widget';
if (~str.indexOf('Widget')) {
console.log('Found it!'); // works
}
Can you explain the function of the string “includes” method?
View Answer:
console.log('Widget with id'.includes('Widget')); // true
console.log('Hello'.includes('Bye')); // false
// The optional second argument:
console.log('Widget'.includes('id')); // true
console.log('Widget'.includes('id', 3)); // false, from position 3 there is no "id"
The includes() method is case sensitive.
Can you explain the function of both string startsWith() and endsWith() methods?
View Answer:
The startsWith() method determines whether a string begins with the characters of a specified string. This method returns true if the string begins with the characters and false if not. The startsWith() method accepts two arguments search value and start position, and by default, the start position gets set to zero (0).
The endsWith() method determines whether a string ends with the characters of a specified string. This method returns true if the string ends with the characters and false if not. The endsWith() method accepts two arguments search value and length. If omitted, the default value is the length of the string.
// startsWith() Method
var str1 = 'Hello world, welcome to the universe.';
var n = str1.startsWith('world', 6);
console.log(n); // returns true
// endsWith() Method
var str2 = 'Hello world, welcome to the universe.';
var o = str2.endsWith('world', 11);
console.log(o); // returns true
Both the startsWith() and endsWith() methods are case sensitive.
What are the three substring methods in JavaScript?
View Answer:
let str = 'Hello, JavaScript!';
console.log(str.substring(0, 5)); // "Hello"
console.log(str.substr(7, 10)); // "JavaScript"
console.log(str.slice(-1)); // "!"
Can you explain the function of the string slice() method in JavaScript?
View Answer:
let str = 'stringify';
console.log(str.slice(0, 5)); // 'strin', the substring from 0 to 5 (not including 5)
console.log(str.slice(0, 1)); // 's', from 0 to 1, but not including 1, so only character at 0
let str = 'stringify';
// start at the 4th position from the right, end at the 1st from the right
console.log(str.slice(-4, -1)); // 'gif'
let str = 'Hello world!';
console.log(str.slice(-5)); // returns world!
Can you describe the purpose of the substring() method?
View Answer:
Syntax: str.substring(start, end)
let str = 'stringify';
// these are same for substring
console.log(str.substring(2, 6)); // "ring"
console.log(str.substring(6, 2)); // "ring"
// ...but not for slice:
console.log(str.slice(2, 6)); // "ring" (the same)
console.log(str.slice(6, 2)); // "" (an empty string)
Can you describe the purpose of the substr() method in JavaScript?
View Answer:
let str = 'stringify';
console.log(str.substr(2, 4)); // 'ring', from the 2nd position get 4 characters
// The first argument may be negative, to count from the end:
let str = 'stringify';
console.log(str.substr(-4, 2)); // 'gi', from the 4th position get 2 characters
The substr()
method does not change the original string.
What is the minor drawback to using the string substr() method in JavaScript?
View Answer:
let str = 'stringify';
console.log(str.substr(2, 4)); // 'ring', from the 2nd position get 4 characters
// The first argument may be negative, to count from the end:
let str = 'stringify';
console.log(str.substr(-4, 2)); // 'gi', from the 4th position get 2 characters
The substr()
method does not change the original string.
Which one is the most flexible choice of the three, substring, slice, and substring methods?
View Answer:
let str = 'Hello, JavaScript!';
console.log(str.slice(-6, -1)); // "JavaScript"
In this example, slice()
is used to get the word "World" from the string by using negative indices.
What does the acronym U.T.F. stand for in JavaScript?
View Answer:
Although JavaScript handles most Unicode and encoding matters internally, you can interact with Unicode characters and their representations in various ways.
let str = 'Hello, JavaScript!';
// Get the Unicode value of the first character in a string (H)
let unicode = str.charCodeAt(0);
console.log(unicode); // 72
// Convert a Unicode value back into a character
let character = String.fromCharCode(72);
console.log(character); // H
// Using Unicode escape sequences in strings:
let unicodeStr = '\u0048ello, JavaScript!';
console.log(unicodeStr); // Hello, JavaScript!
// From ES6 onwards, JavaScript allows using Unicode code points beyond the 16-bit limit using the following syntax:
let astro = '\u{1F680}';
console.log(astro); // 🚀
In this example, the charCodeAt
method is used to get the Unicode value (UTF-16 code unit) of the character at position 0, which is 'H'. The fromCharCode
method is used to convert a Unicode value back into a character.
The last two parts show how you can include Unicode characters directly in a string using escape sequences. The 'H' character has the Unicode value 0048, and you can include it in a string using '\u0048'. The last example shows an ES6 feature where Unicode code points beyond the 16-bit limit can be included using the '\u{...}' syntax. In this case, '1F680' is the Unicode code point for the rocket emoji.
How are strings compared in JavaScript?
View Answer:
Are lowercase letters greater than uppercase letters in JavaScript?
View Answer:
console.log('a' > 'Z'); // true a = 97, Z = 90, so 97 is greater than 90
Are there any special methods we can use to get the UTF-16 number code of a character?
View Answer:
// different case letters have different codes
console.log('z'.codePointAt(0)); // numeric code: 122
console.log('Z'.charCodeAt(0)); // numeric code: 90
What is the main difference between charCodeAt() and codePointAt()?
View Answer:
let str = '𠮷a'; // '𠮷' is an astral symbol
console.log(str.charCodeAt(0)); // 55362
console.log(str.codePointAt(0)); // 134071
The first character '𠮷' is an astral symbol that lies outside the BMP. charCodeAt(0)
returns 55362, which is the code for the high surrogate of the surrogate pair that represents '𠮷'. codePointAt(0)
, however, returns 134071, which is the actual Unicode code point of '𠮷'.
Is there a built-in method to compare diacritical characters in JavaScript?
View Answer:
console.log('Österreich'.localeCompare('Zealand')); // -1
What are the rare symbols encoded with a pair of 2-byte characters?
View Answer:
console.log('𝒳'.length); // 2, MATHEMATICAL SCRIPT CAPITAL X
console.log('😂'.length); // 2, FACE WITH TEARS OF JOY
console.log('𩷶'.length); // 2, a rare Chinese hieroglyph
What modern method can return the numeric code of surrogate pairs?
View Answer:
let str = '𝒳';
let surgPair = str.codePointAt(0);
console.log(surgPair); // returns 119987
What is the difference between accessing string characters with square brackets and using the charAt() method?
View Answer:
let str = "Hello";
// Using square brackets
console.log(str[1]); // 'e'
console.log(str[5]); // undefined
// Using charAt()
console.log(str.charAt(1)); // 'e'
console.log(str.charAt(5)); // ''
What is the difference between UTF-16 and UTF-8 in JavaScript?
View Answer:
let encoder = new TextEncoder(); // Default is 'utf-8'
let decoder = new TextDecoder('utf-8');
let str = "Hello UTF-8";
let encoded = encoder.encode(str);
console.log(encoded); // Uint8Array(10) [72, 101, 108, 108, 111, 32, 85, 84, 70, 45, 56]
let decoded = decoder.decode(encoded);
console.log(decoded); // "Hello UTF-8"
It's important to note that JavaScript strings are sequences of UTF-16 code units, so converting to and from UTF-8 is necessary when interacting with systems that use UTF-8.