Introduction & Syntax
String Methods · Study material
Most real-world text processing – cleaning form input, formatting invoices, building URLs, parsing logs, validating emails – is done with JavaScript's string methods, often together with regular expressions. Interviews test the details: replace with a string changes only the first match, replaceAll with a regex needs the g flag, match returns null (not an empty array) when nothing is found, a global regex remembers lastIndex, and "file10" < "file2" unless you sort with localeCompare's numeric option. This topic covers the methods and the regex basics behind them. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
Case, trimming and padding
toUpperCase / toLowerCase change case (some characters change length: "ß" becomes "SS"). trim, trimStart and trimEnd remove whitespace – spaces, tabs and line breaks – at the ends only. padStart(length, filler) and padEnd add a repeating filler until the string reaches length; a string that is already long enough is returned unchanged.
const raw = " LearnFrenzy ";
console.log(`[${raw.trim()}] [${raw.trimStart()}] [${raw.trimEnd()}]`);
// padStart / padEnd: pad to a target length (the filler repeats and is cut to fit)
console.log("js".toUpperCase(), "7".padStart(3, "0"), "Total".padEnd(8, ".") + "₹99");
console.log("abc".padStart(2), "5".padStart(4, "ab")); // already long enough → unchanged
[LearnFrenzy] [LearnFrenzy ] [ LearnFrenzy] JS 007 Total...₹99 abc aba5
Searching
| Method | Returns | Notes |
|---|---|---|
indexOf(s, from) / lastIndexOf(s, from) | position or -1 | exact text, case-sensitive |
search(regex) | position or -1 | takes a regular expression; ignores g |
includes(s, from) | boolean | cannot take a regex |
startsWith(s, pos) / endsWith(s, endPos) | boolean | endsWith treats the string as ending at endPos |
const s = "The quick brown fox jumps over the lazy dog";
console.log(s.indexOf("the"), s.toLowerCase().indexOf("the"), s.lastIndexOf("o"), s.search(/[aeiou]{2}/));
// includes / startsWith / endsWith take a position: where to start (or, for endsWith, where to end)
console.log(s.includes("fox", 20), s.startsWith("quick", 4), s.endsWith("lazy", 39));
31 0 41 5 false true true
replace and replaceAll
With a string pattern, replace changes only the first occurrence and replaceAll changes every one. With a regex, add the g flag to replace all matches – and replaceAll throws a TypeError if the regex lacks g. In the replacement string, $& inserts the whole match and $1, $2 … the capture groups. A replacer function receives the match, the groups, the offset and the whole string, and returns the replacement.
const msg = "cats and cats and cats";
console.log(msg.replace("cats", "dogs")); // a string pattern: first match only
console.log(msg.replaceAll("cats", "dogs")); // every match
// A regex with g + a replacer function: (match, ...groups, offset, input)
console.log(msg.replace(/cats/g, (m, offset) => `${m.toUpperCase()}@${offset}`));
// $1, $2 … insert capture groups
console.log("2026-11-30".replace(/(\d+)-(\d+)-(\d+)/, "$3/$2/$1"));
dogs and cats and cats dogs and dogs and dogs CATS@0 and CATS@9 and CATS@18 30/11/2026
split with limits and regular expressions
split accepts a string or a regex as separator and an optional limit on the number of pieces. Splitting on a single space keeps empty strings where spaces repeat; /\s+/ treats any run of whitespace as one separator.
console.log("a, b,c , d".split(/\s*,\s*/)); // comma with any spaces around it
console.log("one two three".split(" "), "one two three".split(/\s+/));
console.log("2026-11-30".split("-", 2).map(Number)); // limit the number of pieces
[ 'a', 'b', 'c', 'd' ] [ 'one', 'two', '', 'three' ] [ 'one', 'two', 'three' ] [ 2026, 11 ]
match and matchAll
str.match(regex) without g returns the first match with its capture groups (and index); with g it returns an array of all matched strings, without groups. Either way it returns null when nothing matches. str.matchAll(regex) requires g and returns an iterator of full match objects, including named groups ((?<name>…)) and positions.
const text = "Order #101 shipped, #205 pending, #330 delivered";
console.log(text.match(/#\d+/g)); // with g: every match (no group details)
console.log(text.match(/#(\d+)/)[1]); // without g: the first match and its groups
console.log("no digits".match(/\d/)); // no match: null, not []
// matchAll (needs g) gives each match with its groups and index
for (const m of text.matchAll(/#(?<id>\d+) (?<status>\w+)/g)) {
console.log(m.groups.id, m.groups.status, m.index);
}
[ '#101', '#205', '#330' ] 101 null 101 shipped 6 205 pending 20 330 delivered 34
Comparing and normalising
a.localeCompare(b, locale, options) compares like a dictionary. { numeric: true } sorts "file2" before "file10", and { sensitivity: "base" } ignores case and accents. Unicode allows the same visible text in different forms (é as one character or as e + accent); normalize("NFC") converts both to the same form before comparing.
const files = ["file10.txt", "file2.txt", "File1.txt"];
console.log(files.toSorted()); // code-unit order
console.log(files.toSorted((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })));
// The same visible text can be stored in two ways; normalize() makes them comparable
const a = "café", b = "café";
console.log(a === b, a.length, b.length, a === b.normalize("NFC"));
[ 'File1.txt', 'file10.txt', 'file2.txt' ] [ 'File1.txt', 'file2.txt', 'file10.txt' ] false 4 5 true
Regular expression essentials
A regex literal is written /pattern/flags; new RegExp(text, flags) builds one from a string. Common flags: g (all matches), i (ignore case), m (^ and $ match at line breaks), s (. matches line breaks), u (Unicode). regex.test(str) returns a boolean – but a regex with g or y keeps its lastIndex between calls, so reusing it can give alternating results.
const emailRe = /^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i; // i: ignore case
console.log(["asha@lf.in", "bad@", "R.K+news@Mail.COM"].map((e) => emailRe.test(e)));
// A global regex remembers where it stopped (lastIndex) between test() calls
const g = /a/g;
console.log(g.test("banana"), g.lastIndex, g.test("banana"), g.lastIndex);
[ true, false, true ] true 2 true 4
Common mistakes
- replace("a", "b") to change every "a" – only the first; use replaceAll or /a/g.
- replaceAll(/x/, …) or matchAll(/x/) without g – TypeError.
- str.match(...)[0] without a null check – TypeError when nothing matches.
- Building a RegExp from user input – escape special characters first.
- Reusing a global regex with test() – lastIndex carries over between calls.
- Calling string methods on numbers – convert with String() before padStart.
- Sorting names with numbers by default – "file10" comes before "file2".
Key points to remember
- All string methods return new strings – store the result.
- replace with a string: first match; replaceAll or /g: every match.
- $& = whole match, $1 = first group; replacer functions get (match, …groups, offset, string).
- match returns null when nothing matches; with g it returns strings only.
- matchAll and replaceAll need a g flag on regex arguments.
- padStart/padEnd never shorten a string.
- localeCompare with { numeric: true } sorts numbers inside text naturally.
Frequently asked questions
Should I use a regex or string methods?
Use simple methods (includes, startsWith, split, replaceAll) for fixed text – they are clearer and need no escaping. Use a regex for patterns: "any digits", "one or more spaces", "an email shape".
How do I replace text case-insensitively?
Use a regex with the i flag (and g for every match): str.replace(/javascript/gi, "JavaScript").
Is a regex enough to validate an email?
A simple pattern catches obvious typos; full validation is done by sending a confirmation email. Avoid over-complicated patterns that reject valid addresses.
Where can I learn more?
Read JavaScript String Methods and Regular Expressions in the JavaScript tutorial, then practise with the exercises below.