🔍 String Indexing & Slicing

Last Updated: 6nd October 2025


📌 1. Indexing in Strings

  • Indexing means accessing individual characters in a string.
  • Index starts from 0 (left to right).
  • You can also use negative indexing indirectly (right to left, starting from -1 using slice() or at() method).
  • e.g. let a = "Hello World!", see a visual below

string_variable

Hinglish Tip 🗣: Indexing ka matlab hai string ke andar ek specific position par character ko access karna.

Syntax:

string_variable[index];

Example:

let a = "Hello World!";

// Positive Indexing
console.log(a[0]); // Output: 'H' (first character)
console.log(a[3]); // Output: 'l' (fourth character)
console.log(a[5]); // Output: ' ' (sixth character i.e. space)

// Negative Indexing
console.log(a.at(-1)); // Output: '!'

📌 2. Slicing in Strings

  • Slicing means extracting a portion of a string.
  • It allows you to select a range of characters from a string.

Hinglish Tip 🗣: Slicing me hum ek part (substring) nikalte hain. End index par wala character include nahi hota.

Syntax:

string_variable.slice(startIndex, endIndex);

Here,

  • start_index → starting index (included)
  • end_index → ending index (excluded)

Example:

let text = "JavaScript";
console.log(text.slice(0, 3)); // Jav (0 to 2)
console.log(text.slice(4)); // Script (from index 4 to end)
console.log(text.slice(-6)); // Script (last 6 characters)