JavaScript String and Events: string types; string functions (concat(), split(), indexOf(), lastIndexOf(), substring(), trim(), slice(), replace(), charAt())

JavaScript strings are immutable text, so every string method returns a NEW string rather than changing the original, and the toolkit covers joining (concat), splitting (split), searching (indexOf/lastIndexOf, which return -1 when not found), extracting (slice, substring, charAt), and cleaning (trim, replace).

10 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

' aditi ' is not 'Aditi'

A student types their name into FestConnect as " aditi ", with stray spaces and lowercase. You want a clean "Aditi", you want to split "Aditi Shah" into first and last, and you want to confirm the email actually contains an @.

All of this is string work. JavaScript strings come with a toolkit of methods, but they share one rule that trips everyone: a string can never be changed in place. Every method hands you a new string.

Formula

Strings are immutable

You cannot edit a string; you can only make a new one from it.

name.trim() does not clean name. It returns a trimmed copy and leaves name untouched. You must capture it:

name = name.trim();

Forget the assignment and it looks like the method 'did nothing'. This single rule explains most string bugs. Every method below returns a value you must use.

At a glance

The string toolkit

MethodDoesNote
trim()remove edge spacesreturns a copy
split(sep)break into an array"a b".split(" ")
indexOf(x)first position of x-1 if not found
lastIndexOf(x)last position of x-1 if not found
slice(a,b)chars a..b-1allows negatives
charAt(i)the char at i"" if out of range
replace(a,b)swap first matchreplaceAll for all

Practical

FestConnect cleans a name and checks an email

let raw = "  aditi shah ";
let name = raw.trim();          // "aditi shah" (captured!)
console.log(raw);               // still "  aditi shah " (unchanged)

let parts = name.split(" ");    // ["aditi", "shah"]
console.log(parts[0], parts[1]);

let email = "aditi@x.com";
console.log(email.indexOf("@"));   // 5  (found)
console.log(email.indexOf("?"));   // -1 (not found)

console.log(email.slice(0, 5));    // "aditi"
console.log(email.charAt(0));      // "a"
console.log("a b c".replace(" ", "_")); // "a_b c" (first only)

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Think first

Why did the name stay dirty?

A student writes name.trim(); on its own line, then submits name and it still has spaces. What did they forget, and what is the corrected line?

Show the answer

They forgot to capture the result. name.trim() returns a cleaned copy but does not modify name, because strings are immutable. The fix is to assign it back: name = name.trim();. This one habit, remembering that string methods return a new value you must store, prevents the most common string bug in the whole language.

Quiz

You check `if (email.indexOf("@") )` to see whether an email contains @. Why can this be wrong?

  1. If @ is at position 0, indexOf returns 0, which is falsy, so a valid case is rejected
  2. indexOf returns true or false, not a number
  3. indexOf cannot search for the @ symbol
  4. Nothing is wrong; this always works correctly
Show the answer

If @ is at position 0, indexOf returns 0, which is falsy, so a valid case is rejected

indexOf returns a position number, or -1 if absent, not a boolean. Position 0 is a real match but is falsy, so if (indexOf(...)) treats an @ at the very start as 'not found' (A). Also -1 is truthy, so a missing @ would pass. The correct test is explicit: if (email.indexOf("@") !== -1). indexOf definitely returns a number (B) and can find @ (C), so 'always works' (D) is false.

Watch out

String traps

1. Not capturing the result: s.trim(), s.replace(...), s.toUpperCase() all return copies. Assign them.

2. Testing indexOf as a boolean: it returns a position or -1. Always compare !== -1, never rely on truthiness (0 is a valid position but falsy).

3. slice vs substring: both extract, but slice(-3) counts from the end while substring treats negatives as 0. Reach for slice when you want 'last N characters'.

Theory

This is the heart of validation

In Unit 5 you will validate an email by checking it has an @ and a . after it, and a mobile number by trimming spaces and checking length, all with the methods here. trim, indexOf, split, and slice are the everyday tools of form validation. The next lesson wires these reactions to user actions with events.

Summary

Key takeaways

  • Strings are immutable: every method returns a NEW string, so capture it (name = name.trim()).
  • Join with concat or +; split(sep) breaks a string into an array.
  • indexOf / lastIndexOf give a position or -1 when not found: test with !== -1, never as a boolean.
  • slice, substring, charAt extract parts; slice allows negative indices for 'from the end'.
  • trim() removes edge spaces; replace() swaps the first match (replaceAll for all).
  • Memory hook: string methods return a copy, so store it.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Overview of JavaScript

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

JavaScript String and Events: string types; string functions (concat(), split(), indexOf(), lastIndexOf(), substring(), trim(), slice(), replace(), charAt()) · Web Designing-1 (option A) · Gri-Learn