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.
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 ${}
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");
}
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);
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("-", " "));
No split tab
Cookie preferences
We use necessary cookies to run the site. With your permission, we can also save your site preferences and use analytics and advertising cookies to understand usage and support the project.
Open tools in tabs.Exercises, IDE tools, and trainers stay available as site tabs.
Switch without losing context.Move between explanations, code, and utilities while keeping your place.
Use the sidebar as your map.The left panels hold navigation, settings, files, libraries, and tool controls.
PythonJavaScriptSQLite
One IDE, three practical modes
Python in the browser.Run small scripts, try libraries, and practice API requests without installing anything.
JavaScript for quick experiments.Test browser-friendly code and compare ideas next to your learning materials.
SQLite for data practice.Open the database explorer to inspect tables, write queries, and learn SQL workflows locally.
TopicIDE
Work side by side with split tabs
Keep instructions visible.Open an exercise or reference page beside the IDE instead of jumping back and forth.
Compare tools while you learn.Place regex checks, explanations, and code experiments next to each other when the task needs it.
Close the split when you are done.The workspace returns to a single focused tab, and your open site tabs remain available.
Code Typing Trainer
Or plain text
This trainer is designed for a physical keyboard.Open this section on a laptop or desktop with a wide screen. Touch typing practice will not work correctly on a phone.
Speed: 0 chars/min
0 words/min
Best speed (60s): 0 chars/min
0 words/min
Errors: 0
Total time: 0.0 s
To practice touch typing, avoid looking at your physical keyboard.