JavaScript Strings

What is a String?

1. A string is a sequence of characters enclosed in single quotes, double quotes or backticks.

2. It is a primitive data type in JavaScript.

3. Strings are immutable - once created, their characters cannot be changed.

4. The internal format for strings is always UTF-16, regardless of the page encoding.

String Indexing

let str = "Hello";
// Indices:  01234
          
// Access characters using index
console.log(str[0]);     // "H"
console.log(str[4]);     // "o"
console.log(str[-1]);    // undefined (use at() for negative indices)
console.log(str.at(-1)); // "o" (last character)

String Access Methods

let str = "JavaScript";

// Different ways to access characters
console.log(str[0]);        // "J"
console.log(str.charAt(0)); // "J"
console.log(str.at(0));     // "J"

// Out of range behavior
console.log(str[20]);        // undefined
console.log(str.charAt(20)); // "" (empty string)
console.log(str.at(-1));     // "t" (last character)
console.log(str.at(-2));     // "p" (second to last)

String Characteristics

let str = "Hello";

// Immutability
str[0] = "h";         // No effect
console.log(str);     // Still "Hello"

// Case sensitivity
console.log("Hello" === "hello"); // false

// Unicode support
let text = "Hello 👋 World 🌍";
console.log(text.length);    // Length includes emoji characters
console.log(text[6]);        // "👋" (emoji is a single character)

Types of Strings

1. There are three types of string in JavaScript:

let single = 'single-quoted';
let double = "double-quoted"; 
let backticks = `backticks`;

2. Single and double quotes are essentially the same.

3. Backticks allow:

4. Example of template literals:

let name = "John";
let greeting = `Hello, ${name}!`; // Hello, John!

let multiline = `
  Line 1
  Line 2
  Line 3
`;

String Methods

1. length

let str = "Hello";
console.log(str.length); // 5

let empty = "";
console.log(empty.length); // 0

2. at(index)

let str = "Hello";
console.log(str.at(0));  // H
console.log(str.at(-1)); // o (last character)
console.log(str.at(-2)); // l (second to last)

21. matchAll(regexp)

let str = "Test1 test2 TEST3";

// g flag is required for matchAll
// i flag for case-insensitive matching
let matches = [...str.matchAll(/test\d/gi)];

// Each match object contains:
// - The full match
// - Index where match was found
// - Input string
// - Groups (if any)
console.log(matches);
// [
//   ['Test1', index: 0, input: 'Test1 test2 TEST3', groups: undefined],
//   ['test2', index: 6, input: 'Test1 test2 TEST3', groups: undefined],
//   ['TEST3', index: 12, input: 'Test1 test2 TEST3', groups: undefined]
// ]

// Using capture groups with g flag
let str2 = "2023-03-14 2024-01-01";
let dateMatches = [...str2.matchAll(/(\d{4})-(\d{2})-(\d{2})/g)];
dateMatches.forEach(match => {
  console.log(`Full date: ${match[0]}`);
  console.log(`Year: ${match[1]}, Month: ${match[2]}, Day: ${match[3]}`);
});

String Practice Questions

Special Characters

Escaping Special Characters

Examples:

// Displaying quotes
let str1 = "He said \"Hello\"";        // He said "Hello"
let str2 = 'It\'s a nice day';          // It's a nice day
let str3 = `Use \` for template`;     // Use ` for template

// Displaying paths
let windowsPath = "C:\\Program Files\\Apps";  // C:\Program Files\Apps
let unixPath = "/home/user/docs";             // /home/user/docs

// Multiline strings
let multiline = "First line\nSecond line\nThird line";
/* Output:
First line
Second line
Third line */

// Mixing quotes
let html = "
It\'s a \"quoted\" text
"; //
It's a "quoted" text
// Unicode characters let unicode = "\u00A9 2024"; // © 2024 let emoji = "\u{1F600}"; // 😀

HTML Entity References

// In HTML/JSX
<div>She said &quot;Hello&quot;</div>     // She said "Hello"
<div>It&apos;s working</div>              // It's working
<div>Price: 10&amp;20</div>               // Price: 10&20
<div>1 &lt; 2 &amp;&amp; 3 &gt; 2</div>   // 1 < 2 && 3 > 2