Skip to main content

String Methods

Strings might be primitives logically, but JavaScript temporarily wraps them in a String Object under the hood to let you use these powerful methods.

1. Transformative Methods

  • toUpperCase() / toLowerCase(): Converts casing.
  • trim(): Strips whitespace from the beginning and end.
let text = " Hello World ";
console.log(text.trim().toUpperCase()); // "HELLO WORLD"

2. Extraction Methods

  • slice(start, end): Extracts a section.
  • substring(start, end): Very similar to slice (but cannot accept negative indexes).
let word = "JavaScript";
console.log(word.slice(0, 4)); // "Java"

3. Searching Methods

  • indexOf("str"): Returns the index position of the first occurrence. Returns -1 if not found.
  • includes("str"): Highly preferred method returning true or false.
let email = "admin@example.com";
console.log(email.includes("@")); // true

4. Array Conversion

  • split("separator"): Converts a string into an Array based on the delimited separator.
let csvData = "Apple,Banana,Orange";
let arrayData = csvData.split(",");
console.log(arrayData); // ["Apple", "Banana", "Orange"]