Docs
Module-07-Strings
13.1 String Fundamentals
Overview
Strings are sequences of characters used to represent text. JavaScript strings are immutable - once created, they cannot be changed (methods return new strings).
Creating Strings
// String literals (preferred)
const single = 'Hello';
const double = 'World';
const template = `Hello ${name}`;
// String constructor (rarely used)
const str = String(123); // '123'
const strObj = new String('hello'); // String object โ ๏ธ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STRING TYPES โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ 'hello' โ string primitive โ
โ "hello" โ string primitive โ
โ `hello` โ string primitive (template) โ
โ String('hello') โ string primitive โ
โ new String('hello') โ String object (avoid!) โ
โ โ
โ typeof 'hello' โ 'string' โ
โ typeof new String() โ 'object' โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
String Immutability
const str = 'hello';
str[0] = 'H'; // Silently fails
console.log(str); // 'hello' (unchanged)
// Must create new string
const newStr = 'H' + str.slice(1);
console.log(newStr); // 'Hello'
Accessing Characters
const str = 'JavaScript';
// Bracket notation
str[0]; // 'J'
str[4]; // 'S'
str[str.length - 1]; // 't'
// .at() method (ES2022) - supports negative indices
str.at(0); // 'J'
str.at(-1); // 't'
str.at(-2); // 'p'
// charAt() - older method
str.charAt(0); // 'J'
str.charAt(100); // '' (empty string)
// charCodeAt() - get Unicode code
str.charCodeAt(0); // 74 (Unicode for 'J')
// codePointAt() - for emojis/special chars
'๐'.codePointAt(0); // 128512
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ACCESSING CHARACTERS โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ const str = 'Hello'; โ
โ โ
โ Index: 0 1 2 3 4 โ
โ Char: 'H' 'e' 'l' 'l' 'o' โ
โ Negative: -5 -4 -3 -2 -1 (for .at()) โ
โ โ
โ str[0] โ 'H' str.at(-1) โ 'o' โ
โ str[10] โ undefined โ
โ str.charAt(10) โ '' โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
String Length
const str = 'Hello';
console.log(str.length); // 5
// Length is read-only
str.length = 3; // Silently fails
console.log(str.length); // Still 5
// Empty string
''.length; // 0
// Special characters
'Hello\n'.length; // 6 (newline is 1 char)
'๐'.length; // 2 (emoji is 2 code units!)
Escape Sequences
| Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\r | Carriage return |
\uXXXX | Unicode (4 hex digits) |
\xXX | Latin-1 (2 hex digits) |
// Common escape sequences
const newline = 'Line 1\nLine 2';
const tab = 'Col1\tCol2';
const quote = 'He said "Hello"';
const escaped = "It's a test";
const path = 'C:\\Users\\name';
// Unicode
const heart = '\u2764'; // โค
const smiley = '\u{1F600}'; // ๐ (ES6 extended)
Template Literals
// Basic interpolation
const name = 'John';
const greeting = `Hello, ${name}!`;
// Expressions
const a = 5,
b = 3;
console.log(`Sum: ${a + b}`); // 'Sum: 8'
// Multi-line
const html = `
<div>
<p>Hello, ${name}</p>
</div>
`;
// Nested templates
const items = ['a', 'b', 'c'];
const list = `<ul>${items.map((i) => `<li>${i}</li>`).join('')}</ul>`;
// Tagged templates
function highlight(strings, ...values) {
return strings.reduce(
(result, str, i) =>
result + str + (values[i] ? `<mark>${values[i]}</mark>` : ''),
''
);
}
const result = highlight`Hello ${name}, you have ${3} messages`;
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TEMPLATE LITERAL PARTS โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ `Hello ${name}, you are ${age} years old` โ
โ โ
โ strings: ['Hello ', ', you are ', ' years old'] โ
โ values: [name, age] โ
โ โ
โ String parts: 3 โ
โ Value parts: 2 โ
โ strings.length = values.length + 1 โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
String Concatenation
// + operator
const result1 = 'Hello' + ' ' + 'World';
// += operator
let str = 'Hello';
str += ' World';
// concat() method
const result2 = 'Hello'.concat(' ', 'World');
// Template literals (preferred for complex)
const name = 'John';
const result3 = `Hello ${name}`;
// Array join for many parts
const parts = ['Hello', 'World', '!'];
const result4 = parts.join(' '); // 'Hello World !'
Performance Comparison
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CONCATENATION METHODS โ
โโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Method โ Best For โ
โโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ + โ Simple, few strings โ
โ += โ Building in loop (modern JS) โ
โ Template literal โ Interpolation, readability โ
โ Array.join() โ Many strings, separator needed โ
โ concat() โ Rarely preferred โ
โโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Case Conversion
const str = 'Hello World';
// Convert case
str.toLowerCase(); // 'hello world'
str.toUpperCase(); // 'HELLO WORLD'
// Locale-aware (for special characters)
'ร'.toUpperCase(); // 'SS' (German)
'I'.toLocaleLowerCase('tr'); // 'ฤฑ' (Turkish)
// Title case (not built-in)
function toTitleCase(str) {
return str.replace(/\b\w/g, (c) => c.toUpperCase());
}
toTitleCase('hello world'); // 'Hello World'
Searching Strings
Basic Search Methods
| Method | Returns | Purpose |
|---|---|---|
indexOf() | Index or -1 | First occurrence |
lastIndexOf() | Index or -1 | Last occurrence |
includes() | Boolean | Check existence |
startsWith() | Boolean | Check prefix |
endsWith() | Boolean | Check suffix |
search() | Index or -1 | Regex search |
const str = 'Hello World, Hello Universe';
// indexOf / lastIndexOf
str.indexOf('Hello'); // 0
str.lastIndexOf('Hello'); // 13
str.indexOf('hello'); // -1 (case-sensitive)
str.indexOf('o', 5); // 7 (start from index 5)
// includes
str.includes('World'); // true
str.includes('world'); // false
str.includes('World', 10); // false (start from index 10)
// startsWith / endsWith
str.startsWith('Hello'); // true
str.endsWith('Universe'); // true
str.startsWith('World', 6); // true (from index 6)
str.endsWith('World', 11); // true (check first 11 chars)
Extracting Substrings
const str = 'Hello World';
// slice(start, end) - most versatile
str.slice(0, 5); // 'Hello'
str.slice(6); // 'World'
str.slice(-5); // 'World' (from end)
str.slice(-5, -1); // 'Worl'
// substring(start, end) - no negative indices
str.substring(0, 5); // 'Hello'
str.substring(6); // 'World'
str.substring(6, 0); // 'Hello' (swaps if start > end)
// substr(start, length) - DEPRECATED
str.substr(0, 5); // 'Hello'
str.substr(-5, 3); // 'Wor'
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ EXTRACTION METHODS โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ const str = 'Hello World'; โ
โ // 01234567890 โ
โ โ
โ slice(0, 5) โ 'Hello' (index 0-4) โ
โ slice(6) โ 'World' (index 6 to end) โ
โ slice(-5) โ 'World' (last 5 chars) โ
โ slice(-5, -2) โ 'Wor' (index -5 to -3) โ
โ โ
โ โ
Use slice() - most flexible โ
โ โ ๏ธ Avoid substr() - deprecated โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Trimming Whitespace
const str = ' Hello World ';
str.trim(); // 'Hello World'
str.trimStart(); // 'Hello World '
str.trimEnd(); // ' Hello World'
// Aliases (older)
str.trimLeft(); // Same as trimStart()
str.trimRight(); // Same as trimEnd()
// Only trims whitespace (spaces, tabs, newlines)
' \t\n Hello \n\t '.trim(); // 'Hello'
Padding Strings
// padStart(targetLength, padString)
'5'.padStart(3, '0'); // '005'
'42'.padStart(5, '*'); // '***42'
'hello'.padStart(10); // ' hello' (spaces by default)
// padEnd(targetLength, padString)
'5'.padEnd(3, '0'); // '500'
'42'.padEnd(5, '*'); // '42***'
// Practical uses
const price = '9.99';
price.padStart(10, ' '); // ' 9.99' (right-align)
const id = '123';
id.padStart(8, '0'); // '00000123' (zero-pad)
Repeating Strings
// repeat(count)
'abc'.repeat(3); // 'abcabcabc'
'-'.repeat(10); // '----------'
'Hi '.repeat(2); // 'Hi Hi '
// Use cases
const separator = '='.repeat(40);
const indent = ' '.repeat(depth);
Splitting and Joining
// split(separator, limit)
'a,b,c'.split(','); // ['a', 'b', 'c']
'a,b,c'.split(',', 2); // ['a', 'b']
'hello'.split(''); // ['h', 'e', 'l', 'l', 'o']
'hello world'.split(' '); // ['hello', 'world']
'a1b2c3'.split(/\d/); // ['a', 'b', 'c', '']
// join(separator)
['a', 'b', 'c'].join(','); // 'a,b,c'
['a', 'b', 'c'].join(' - '); // 'a - b - c'
['a', 'b', 'c'].join(''); // 'abc'
Replacing Content
const str = 'Hello World, Hello Universe';
// replace(search, replacement) - first occurrence only
str.replace('Hello', 'Hi'); // 'Hi World, Hello Universe'
// replaceAll(search, replacement) - all occurrences
str.replaceAll('Hello', 'Hi'); // 'Hi World, Hi Universe'
// With regex (g flag for global)
str.replace(/Hello/g, 'Hi'); // 'Hi World, Hi Universe'
// Case-insensitive
str.replace(/hello/gi, 'Hi'); // 'Hi World, Hi Universe'
// Replacement patterns
'John Doe'.replace(/(\w+) (\w+)/, '$2, $1'); // 'Doe, John'
// Replacement function
'hello'.replace(/./g, (char, i) => (i === 0 ? char.toUpperCase() : char)); // 'Hello'
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REPLACEMENT PATTERNS โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Pattern โ Meaning โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ $$ โ Literal $ โ
โ $& โ Matched substring โ
โ $` โ Text before match โ
โ $' โ Text after match โ
โ $1, $2... โ Captured groups โ
โ $<name> โ Named captured group โ
โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
String Comparison
// Equality
'hello' === 'hello'; // true
'Hello' === 'hello'; // false (case-sensitive)
// Comparison (lexicographic)
'a' < 'b'; // true
'a' < 'A'; // false (lowercase > uppercase in ASCII)
'10' < '9'; // true (string comparison!)
// localeCompare for proper sorting
'รค'.localeCompare('z'); // -1 (รค before z in German)
'รค'.localeCompare('z', 'sv'); // 1 (รค after z in Swedish)
// Case-insensitive comparison
const a = 'Hello';
const b = 'hello';
a.toLowerCase() === b.toLowerCase(); // true
a.localeCompare(b, undefined, { sensitivity: 'base' }) === 0; // true
Unicode and Special Characters
// String length vs character count
'cafรฉ'.length; // 4
'๐'.length; // 2 (surrogate pair)
[...'๐'].length; // 1 (correct count)
// Iterate properly over Unicode
for (const char of '๐๐') {
console.log(char); // '๐', '๐' (correct)
}
// Spread for array of characters
[...'Hello ๐']; // ['H', 'e', 'l', 'l', 'o', ' ', '๐']
// Normalize for comparison
'cafรฉ'.normalize() === 'cafรฉ'.normalize(); // true
// String from code points
String.fromCodePoint(128512); // '๐'
String.fromCharCode(65); // 'A'
Key Takeaways
- โขStrings are immutable - All methods return new strings
- โขUse template literals - For interpolation and multi-line
- โขUse slice() - Most flexible extraction method
- โขBe careful with emoji - They're 2 code units
- โขUse localeCompare() - For proper internationalized sorting
- โขreplaceAll() vs replace() - replaceAll for global replacement
- โขSpread operator - Best way to split into true characters