String Methods and Manipulation

Beginner
80 XP
30 min
Lesson Content

String Methods and Manipulation

Strings are sequences of characters. JavaScript provides many built-in methods to work with strings, making text manipulation easy and powerful.

Common String Methods

  • length - Get string length: 'Hello'.length // 5
  • toUpperCase() - Convert to uppercase: 'hello'.toUpperCase() // 'HELLO'
  • toLowerCase() - Convert to lowercase: 'HELLO'.toLowerCase() // 'hello'
  • trim() - Remove whitespace: ' text '.trim() // 'text'
  • charAt() - Get character at index: 'Hello'.charAt(0) // 'H'
  • substring() - Extract substring: 'Hello'.substring(0, 2) // 'He'
  • split() - Split into array: 'a,b,c'.split(',') // ['a', 'b', 'c']
  • join() - Join array into string: ['a', 'b'].join('-') // 'a-b'
  • includes() - Check if contains: 'Hello'.includes('ell') // true
  • indexOf() - Find position: 'Hello'.indexOf('l') // 2
  • replace() - Replace text: 'Hello'.replace('H', 'J') // 'Jello'

Template Literals

// Old way (concatenation)
let name = 'John';
let message = 'Hello, ' + name + '!';

// New way (template literals)
let message = `Hello, ${name}!`;

// Multi-line strings
let text = `Line 1
Line 2
Line 3`;

String Comparison

'apple' < 'banana'  // true (alphabetical)
'a' === 'A'        // false (case-sensitive)
'a'.toLowerCase() === 'A'.toLowerCase()  // true
Example Code

Use string methods to transform and analyze text

let text = '  JavaScript is Awesome!  ';

// Remove whitespace
let trimmed = text.trim();
console.log('Trimmed:', trimmed);

// Convert to uppercase
let upper = trimmed.toUpperCase();
console.log('Uppercase:', upper);

// Check if contains 'Awesome'
let hasAwesome = trimmed.includes('Awesome');
console.log('Has Awesome:', hasAwesome);

// Get first word
let words = trimmed.split(' ');
console.log('First word:', words[0]);

// Replace 'Awesome' with 'Great'
let replaced = trimmed.replace('Awesome', 'Great');
console.log('Replaced:', replaced);

Expected Output:

Trimmed: JavaScript is Awesome!
Uppercase: JAVASCRIPT IS AWESOME!
Has Awesome: true
First word: JavaScript
Replaced: JavaScript is Great!
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code