JavaScript · Syntax · Beginner

String Methods

10 tasks

Learn the built-in string methods in JavaScript — searching, slicing, replacing, splitting, and formatting text with template literals.

String methods: searching, transforming, splitting

#
Strings are one of the most-used types in JavaScript, and they come with a rich set of built-in methods. Knowing them replaces a lot of manual loops. `length` is a property, not a method — no parentheses needed: ```javascript let name = "JavaScript"; console.log(name.length); // 10 ``` Case conversion: `toUpperCase()` and `toLowerCase()` return a new string without modifying the original. Strings in JavaScript are immutable — every method returns a new value, it never mutates in place. Trimming whitespace: `trim()` removes spaces, tabs, and newlines from both ends. `trimStart()` and `trimEnd()` handle one side only. This is essential when processing user input, which often arrives with accidental spaces. Searching inside a string: - `includes(sub)` — returns true if the substring exists anywhere - `startsWith(sub)` and `endsWith(sub)` — check only the beginning or end - `indexOf(sub)` — returns the zero-based position, or -1 if not found - `lastIndexOf(sub)` — same but scans from the right Modifying: - `replace(old, new)` — replaces the first match only - `replaceAll(old, new)` — replaces every match - `split(separator)` — converts the string into an array of parts Two common mistakes to avoid: `replace()` only touches the first occurrence. If you need all of them, use `replaceAll()` or a regex with the `g` flag: `replace(/word/g, 'replacement')`. `indexOf()` returns -1 when nothing is found — not null or false. Always compare explicitly: `if (idx !== -1)`, not just `if (idx)`. A result of 0 (substring at position 0) is falsy and would be wrongly treated as "not found". None of these methods change the original string. The result must be stored: `let clean = text.trim()`, not just `text.trim()` on its own.

slice, padStart, template literals, and method chaining

#
These four patterns appear constantly in real code and cover most string-processing tasks you will encounter. **Extracting parts with `slice`** ```javascript let filename = "report_2024.pdf"; let ext = filename.slice(filename.lastIndexOf(".")); // ".pdf" let name = filename.slice(0, filename.lastIndexOf(".")); // "report_2024" ``` `slice(start, end)` uses zero-based indexes and does not include the end position. Negative values count from the right: `slice(-3)` takes the last 3 characters. Combining `slice` with `lastIndexOf` is the standard pattern for splitting filenames or URLs at a known separator. **Padding for fixed-width output** ```javascript let orderNum = 42; console.log(String(orderNum).padStart(6, "0")); // "000042" let label = "ok"; console.log(label.padEnd(10, ".")); // "ok........" ``` `padStart(targetLength, padChar)` fills the left side; `padEnd` fills the right. The number must be converted to a string first — `padStart` only works on strings. This is useful for order numbers, timestamps, and aligning table output. **Template literals** ```javascript let user = "Alice"; let score = 98; console.log(`${user} scored ${score} points`); console.log(`Grade: ${score >= 90 ? "A" : "B"}`); ``` Template literals use backticks, not quotes. Anything inside `${}` is evaluated as a JavaScript expression — you can call functions, use ternaries, do arithmetic. Use them whenever you need to embed a variable into a string; concatenation with `+` gets messy fast. **Method chaining** ```javascript let raw = " Hello, World! "; let result = raw.trim().toLowerCase().replaceAll(",", ""); // "hello world!" ``` Every string method returns a new string, so calls can be chained in one line. Read left to right: first trim the edges, then lowercase, then strip punctuation. Chain only when each step is clear — splitting into variables is better when the logic becomes hard to follow.

String methods reference

#
Quick lookup for JavaScript string methods. All return a new string unless noted. **Inspection** `str.length` — character count (property, no parentheses) `str.includes(sub)` — true if sub appears anywhere `str.startsWith(sub)` — true if str begins with sub `str.endsWith(sub)` — true if str ends with sub `str.indexOf(sub)` — first position of sub, or -1 `str.lastIndexOf(sub)` — last position of sub, or -1 **Transformation** `str.toUpperCase()` — all uppercase `str.toLowerCase()` — all lowercase `str.trim()` — remove whitespace from both ends `str.trimStart()` — remove from the left only `str.trimEnd()` — remove from the right only `str.replace(old, new)` — replace first match `str.replaceAll(old, new)` — replace all matches `str.padStart(len, char)` — pad left to total length len `str.padEnd(len, char)` — pad right to total length len `str.repeat(n)` — repeat the string n times **Extracting** `str.slice(start, end)` — substring by index; end not included; negatives count from the right `str.split(sep)` — split into an array by separator; `split('')` splits into characters **Template literals** `` `Hello, ${name}!` `` — embed any expression with ${} `` `${a > b ? a : b}` `` — ternaries, function calls, arithmetic all work inside ${}
01

Trim and uppercase

#

The variable `text` stores a string with leading and trailing spaces. Trim the whitespace and convert the result to uppercase.

let text = "  hello javascript  ";
// your code here
Solution
let text = "  hello javascript  ";
console.log(text.trim().toUpperCase());
02

Email quick check

#

Check whether the string in `email` contains `"@"` and ends with `".com"`. Print `true` or `false`.

let email = "[email protected]";
// your code here
Solution
let email = "[email protected]";
console.log(email.includes("@") && email.endsWith(".com"));
03

Split into words

#

Split the string `sentence` into an array of individual words and print the array. Words are separated by spaces.

let sentence = "JavaScript has many string methods";
// your code here
Solution
let sentence = "JavaScript has many string methods";
console.log(sentence.split(" "));
04

Replace all occurrences

#

In the string `text`, replace every occurrence of the word `"cat"` with `"dog"` and print the result.

let text = "The cat sat on the mat. The cat liked it.";
// your code here
Solution
let text = "The cat sat on the mat. The cat liked it.";
console.log(text.replaceAll("cat", "dog"));
05

Find substring position

#

Find the position of the first occurrence of `"script"` (case-insensitive) in `text`. If not found — print `"Not found"`, otherwise print the index.

let text = "JavaScript is a scripting language";
// your code here
Solution
let text = "JavaScript is a scripting language";
let idx = text.toLowerCase().indexOf("script");
if (idx !== -1) {
    console.log(idx);
} else {
    console.log("Not found");
}
06

Pad an order number

#

Format the number `orderNum` as a string of exactly 6 characters, padded with zeros on the left. For example: `42` → `"000042"`.

let orderNum = 42;
// your code here
Solution
let orderNum = 42;
console.log(String(orderNum).padStart(6, "0"));
07

Validate a URL

#

Check whether the URL in `url` starts with `"https"` and contains `"."`. Print `true` or `false`.

let url = "https://example.com";
// your code here
Solution
let url = "https://example.com";
console.log(url.startsWith("https") && url.includes("."));
08

Extract filename without extension

#

The variable `path` stores a file path. Extract just the filename without the extension (the part after the last `"/"` and before the last `"."`).

let path = "files/reports/summary_2024.pdf";
// your code here
Solution
let path = "files/reports/summary_2024.pdf";
let filename = path.slice(path.lastIndexOf("/") + 1);
let name = filename.slice(0, filename.lastIndexOf("."));
console.log(name);
09

snake_case to Title Case

#

Convert the `snake_case` string to Title Case: each word capitalized, words separated by spaces. Example: `"hello_world"` → `"Hello World"`.

let text = "hello_world_from_js";
// your code here
Solution
let text = "hello_world_from_js";
let result = text
    .split("_")
    .map(word => word[0].toUpperCase() + word.slice(1))
    .join(" ");
console.log(result);
10

Normalize user input

#

The variable `input` stores raw user input with extra spaces, mixed case, and dashes instead of spaces. Normalize it: trim whitespace, convert to lowercase, replace all dashes with spaces.

let input = "  Hello-World-JavaScript  ";
// your code here
Solution
let input = "  Hello-World-JavaScript  ";
console.log(input.trim().toLowerCase().replaceAll("-", " "));