Module 8: Strings
Strings are sequences of characters used for text representation and manipulation. JavaScript provides powerful string methods for working with text data.
1. Creating Strings
// String literals
const single = 'Hello';
const double = "World";
const template = `Hello, World!`;
// String constructor (avoid)
const str = new String('Hello'); // Returns object, not primitive
2. Template Literals (ES6)
const name = 'John';
const age = 30;
// String interpolation
const greeting = `Hello, ${name}! You are ${age} years old.`;
// Expressions
const total = `Total: $${price * quantity}`;
// Multi-line strings
const html = `
<div>
<h1>${title}</h1>
<p>${content}</p>
</div>
`;
// Tagged templates (advanced)
function highlight(strings, ...values) {
return strings.reduce((acc, str, i) =>
acc + str + (values[i] ? `<mark>${values[i]}</mark>` : ''), ''
);
}
const result = highlight`Hello, ${name}! Age: ${age}`;
3. String Properties
const str = 'Hello, World!';
// length
console.log(str.length); // 13
4. Accessing Characters
const str = 'Hello';
// Bracket notation
str[0]; // 'H'
str[4]; // 'o'
// charAt()
str.charAt(0); // 'H'
str.charAt(10); // '' (empty string, not undefined)
// charCodeAt() - returns UTF-16 code
str.charCodeAt(0); // 72
// at() (ES2022) - supports negative indices
str.at(0); // 'H'
str.at(-1); // 'o'
5. String Methods - Searching
const str = 'Hello, World!';
// indexOf() - first occurrence
str.indexOf('o'); // 4
str.indexOf('o', 5); // 8 (start from index 5)
str.indexOf('xyz'); // -1 (not found)
// lastIndexOf() - last occurrence
str.lastIndexOf('o'); // 8
// includes() - boolean check
str.includes('World'); // true
str.includes('world'); // false (case-sensitive)
// startsWith()
str.startsWith('Hello'); // true
str.startsWith('World', 7); // true (start from index 7)
// endsWith()
str.endsWith('!'); // true
str.endsWith('World', 12); // true (check first 12 chars)
// search() - regex
str.search(/world/i); // 7 (case-insensitive)
6. String Methods - Extraction
const str = 'Hello, World!';
// slice(start, end)
str.slice(0, 5); // 'Hello'
str.slice(7); // 'World!'
str.slice(-6); // 'World!'
// substring(start, end)
str.substring(0, 5); // 'Hello'
str.substring(7); // 'World!'
// substr(start, length) - deprecated
str.substr(7, 5); // 'World'
// split() - convert to array
str.split(','); // ['Hello', ' World!']
str.split(''); // ['H', 'e', 'l', 'l', 'o', ...]
'a,b,c'.split(','); // ['a', 'b', 'c']
7. String Methods - Case Conversion
const str = 'Hello, World!';
// toLowerCase()
str.toLowerCase(); // 'hello, world!'
// toUpperCase()
str.toUpperCase(); // 'HELLO, WORLD!'
// Locale-specific
'istanbul'.toLocaleUpperCase('tr-TR'); // '\u0130STANBUL'
8. String Methods - Modification
const str = 'Hello, World!';
// replace() - first occurrence
str.replace('World', 'JavaScript'); // 'Hello, JavaScript!'
str.replace(/o/g, '0'); // 'Hell0, W0rld!' (global regex)
// replaceAll() (ES2021)
str.replaceAll('o', '0'); // 'Hell0, W0rld!'
// repeat()
'Ha'.repeat(3); // 'HaHaHa'
// concat()
'Hello'.concat(', ', 'World', '!'); // 'Hello, World!'
// Better: use template literals or +
// trim() - remove whitespace
' Hello '.trim(); // 'Hello'
' Hello '.trimStart(); // 'Hello '
' Hello '.trimEnd(); // ' Hello'
// padStart() & padEnd() (ES2017)
'5'.padStart(3, '0'); // '005'
'5'.padEnd(3, '0'); // '500'
9. String Methods - Pattern Matching
const str = 'The quick brown fox jumps over the lazy dog';
// match() - returns array of matches
str.match(/the/gi); // ['The', 'the']
// matchAll() (ES2020) - returns iterator
const matches = str.matchAll(/\b\w{4}\b/g);
for (const match of matches) {
console.log(match[0]); // 'quick', 'brown', 'fox', 'jumps', 'over', 'lazy'
}
// test() - boolean check (regex method)
/quick/.test(str); // true
10. String Comparison
// Equality
'hello' === 'hello'; // true
'hello' === 'Hello'; // false
// localeCompare() - locale-aware comparison
'a'.localeCompare('b'); // -1 (a < b)
'b'.localeCompare('a'); // 1 (b > a)
'a'.localeCompare('a'); // 0 (equal)
// Sort strings
const names = ['Zoe', 'Alice', 'Bob'];
names.sort((a, b) => a.localeCompare(b));
11. Unicode & Emoji
// Unicode escape
'\u0048\u0065\u006C\u006C\u006F'; // 'Hello'
// Emoji
const emoji = '😀';
emoji.length; // 2 (surrogate pair)
[...emoji].length; // 1 (correct count)
// codePointAt()
emoji.codePointAt(0); // 128512
// fromCodePoint()
String.fromCodePoint(128512); // '😀'
// Normalize Unicode
'café'.normalize(); // Combines é into single character
12. Common String Patterns
Capitalize First Letter
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
capitalize('hello'); // 'Hello'
Title Case
function titleCase(str) {
return str
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
titleCase('hello world'); // 'Hello World'
Truncate
function truncate(str, maxLength) {
return str.length > maxLength
? str.slice(0, maxLength - 3) + '...'
: str;
}
truncate('Hello, World!', 10); // 'Hello, ...'
Reverse String
function reverse(str) {
return str.split('').reverse().join('');
}
reverse('hello'); // 'olleh'
// Unicode-safe
function reverseUnicode(str) {
return [...str].reverse().join('');
}
Check Palindrome
function isPalindrome(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleaned === cleaned.split('').reverse().join('');
}
isPalindrome('A man, a plan, a canal: Panama'); // true
13. Regular Expressions with Strings
// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailRegex.test('user@example.com'); // true
// Extract numbers
'Price: $29.99'.match(/\d+\.\d+/)[0]; // '29.99'
// Replace multiple spaces with single space
'Hello World'.replace(/\s+/g, ' '); // 'Hello World'
// Extract hashtags
'Hello #world #javascript'.match(/#\w+/g); // ['#world', '#javascript']
14. String Conversion
// Number to String
String(123); // '123'
(123).toString(); // '123'
123 + ''; // '123'
// Array to String
[1, 2, 3].toString(); // '1,2,3'
[1, 2, 3].join('-'); // '1-2-3'
// Object to String
JSON.stringify({ name: 'John' }); // '{\"name\":\"John\"}'
15. Performance Tips
// String concatenation in loops
// Bad
let result = '';
for (let i = 0; i < 1000; i++) {
result += 'text';
}
// Good - use array join
const parts = [];
for (let i = 0; i < 1000; i++) {
parts.push('text');
}
const result = parts.join('');
// Best - template literal
const result = `text`.repeat(1000);
Summary
In this module, you learned:
- ✅ String creation and template literals
- ✅ String properties and character access
- ✅ Searching and extracting substrings
- ✅ Case conversion and modification
- ✅ Pattern matching with regex
- ✅ Unicode and emoji handling
- ✅ Common string manipulation patterns
Next Steps
In Module 9, you'll learn about Numbers and Math for numerical operations.
Practice Exercises
- Implement a function to count vowels in a string
- Write a slug generator (URL-friendly string)
- Create a function to mask email addresses
- Implement word count and character count functions
- Build a simple template engine using regex
- Create a function to extract URLs from text
- Implement string compression (count repeated characters)
- Write a function to validate strong passwords
Additional Resources
- MDN: String
- JavaScript.info: Strings
- Regex101 - Test regular expressions