Back to course

Manipulating Strings: Slicing, Searching, and Substrings

JavaScript: The Complete '0 to Hero' Beginner Course

17. String Manipulation Methods

1. Finding Substrings: .indexOf() and .includes()

  • .indexOf(substring): Returns the index of the first occurrence of the substring. Returns -1 if not found.
  • .includes(substring): Returns true or false if the substring is present.

javascript let sentence = 'The cat sat on the mat.';

console.log(sentence.indexOf('cat')); // Output: 4 console.log(sentence.indexOf('dog')); // Output: -1 console.log(sentence.includes('sat')); // Output: true

2. Extracting Parts: .slice()

.slice(start, end) extracts a section of a string and returns it as a new string. The end index is exclusive.

javascript let data = 'ProductCode:X23Y';

// Get characters from index 12 up to the end: let code = data.slice(12); console.log(code); // Output: X23Y

// Get characters from index 0 up to (but not including) index 11: let prefix = data.slice(0, 11); console.log(prefix); // Output: ProductCode

3. Removing Whitespace: .trim()

Removes whitespace characters from both ends of a string.

javascript let login = ' user@email.com '; console.log(login.trim()); // Output: user@email.com