Skip to content

Commit f05948c

Browse files
fix: multiple findings till substring()
1 parent 9dcd09f commit f05948c

1 file changed

Lines changed: 35 additions & 35 deletions

File tree

data/blog/software-development/web-development/frontend/javascript/slice-vs-substring-vs-substr-complete-javascript-string-methods-comparison.mdx

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ Comparison of `String.prototype.slice()`, `String.prototype.substring()`, and `S
4646
| **Start > End** | Returns empty string | Swaps arguments | Works as expected |
4747
| **Status** | Recommended ✅ | Supported ⚠️ | Deprecated ❌ |
4848

49-
## Understanding slice() / String.prototype.slice()
49+
## Understanding `slice()` / `String.prototype.slice()`
5050

5151
The `String.prototype.slice()` method (commonly called `slice()`) extracts a section of a string and returns it as a new string, without modifying the original string. It's the most modern and recommended method for extracting substrings in JavaScript. `slice()` was introduced in ECMAScript 3 and is part of the official JavaScript specification, making it the standard choice for string extraction operations.
5252

@@ -58,20 +58,20 @@ string.slice(startIndex, endIndex)
5858

5959
### Parameters
6060

61-
- **startIndex**: The zero-based index at which to begin extraction. Can be negative (counts from end). If negative, it's converted to `string.length + startIndex`. If omitted or undefined, defaults to 0.
62-
- **endIndex** (optional): The zero-based index **before which** to end extraction (exclusive). Can be negative (counts from end). If negative, it's converted to `string.length + endIndex`. If omitted or undefined, defaults to `string.length`. If `endIndex` is greater than `string.length`, it's clamped to `string.length`.
61+
- **`startIndex`**: The zero-based index at which to begin extraction. Can be negative (counts from end). If negative, it's converted to `string.length + startIndex`. If undefined, defaults to 0. If greater than `string.length`, it's clamped to `string.length`.
62+
- **`endIndex`** (optional): The zero-based index **before which** to end extraction (exclusive). Can be negative (counts from end). If negative, it's converted to `string.length + endIndex`. If omitted or undefined, defaults to `string.length`. If greater than `string.length`, it's clamped to `string.length`.
6363

64-
### Key Features of slice()
64+
### Key Features of `slice()`
6565

6666
1. **Supports Negative Indices**: Negative indices count backwards from the end of the string, making it intuitive to extract from the end
6767
2. **No Argument Swapping**: If `start > end`, returns an empty string (predictable behavior)
6868
3. **Consistent Behavior**: Predictable and intuitive behavior across all scenarios
69-
4. **Similar to Array.slice()**: Works identically to `Array.prototype.slice()`, providing consistency across JavaScript APIs
69+
4. **Similar to `Array.slice()`**: Works identically to `Array.prototype.slice()`, providing consistency across JavaScript APIs
7070
5. **Immutable**: Never modifies the original string, always returns a new string
7171
6. **Clamps Indices**: Automatically handles out-of-bounds indices gracefully
7272
7. **Exclusive End Index**: The end index is exclusive (not included in the result), which is consistent with many programming languages
7373

74-
### Why slice() is Recommended
74+
### Why `slice()` is Recommended
7575

7676
`slice()` is the recommended method because:
7777

@@ -82,7 +82,7 @@ string.slice(startIndex, endIndex)
8282
- **Predictable**: No surprising argument swapping or type coercion quirks
8383
- **Future-proof**: Not deprecated, actively maintained and optimized
8484

85-
### slice() Examples
85+
### `slice()` Examples
8686

8787
#### Basic Usage Examples
8888

@@ -235,43 +235,43 @@ console.log(str.slice(2.7, 5.9)); // "vaS"
235235
// Equivalent to: str.slice(2, 5)
236236
```
237237

238-
### slice() with Negative Indices Explained (Visual Guide)
238+
### `slice()` with Negative Indices Explained (Visual Guide)
239239

240240
Understanding negative indices is crucial for effective string manipulation. Here's a detailed visual explanation:
241241

242242
```javascript
243-
const str = "Hello World";
244-
// String length: 11 characters
243+
const str = "JavaScript";
244+
// String length: 10 characters
245245

246246
// Visual representation with positive indices:
247-
// Character: H e l l o W o r l d
248-
// Index: 0 1 2 3 4 5 6 7 8 9 10
247+
// Character: J a v a S c r i p t
248+
// Index: 0 1 2 3 4 5 6 7 8 9
249249

250250
// Visual representation with negative indices:
251-
// Character: H e l l o W o r l d
252-
// Index: -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
251+
// Character: J a v a S c r i p t
252+
// Index: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
253253

254254
// Formula: negativeIndex = string.length + negativeValue
255-
// Example: -5 in "Hello World" (length 11) = 11 + (-5) = 6
255+
// Example: -5 in "JavaScript" (length 10) = 10 + (-5) = 5
256256

257-
console.log(str.slice(-5)); // "World"
257+
console.log(str.slice(-6)); // "Script"
258258
// Step-by-step:
259-
// 1. Convert -5: 11 + (-5) = 6
260-
// 2. Start index: 6 (character 'W')
261-
// 3. End index: 11 (end of string, default)
262-
// 4. Extract: indices 6, 7, 8, 9, 10 → "World"
259+
// 1. Convert -6: 10 + (-6) = 4
260+
// 2. Start index: 4 (character 'S')
261+
// 3. End index: 10 (end of string, default)
262+
// 4. Extract: indices 4, 5, 6, 7, 8, 9 → "Script"
263263

264-
console.log(str.slice(-5, -1)); // "Worl"
264+
console.log(str.slice(-6, -1)); // "Scrip"
265265
// Step-by-step:
266-
// 1. Convert start -5: 11 + (-5) = 6
267-
// 2. Convert end -1: 11 + (-1) = 10
268-
// 3. Extract: indices 6, 7, 8, 9 (exclusive of 10) → "Worl"
266+
// 1. Convert start -6: 10 + (-6) = 4
267+
// 2. Convert end -1: 10 + (-1) = 9
268+
// 3. Extract: indices 4, 5, 6, 7, 8 (exclusive of 9) → "Scrip"
269269

270-
console.log(str.slice(0, -6)); // "Hello"
270+
console.log(str.slice(0, -6)); // "Java"
271271
// Step-by-step:
272-
// 1. Start index: 0 (character 'H')
273-
// 2. Convert end -6: 11 + (-6) = 5
274-
// 3. Extract: indices 0, 1, 2, 3, 4 (exclusive of 5) → "Hello"
272+
// 1. Start index: 0 (character 'J')
273+
// 2. Convert end -6: 10 + (-6) = 4
274+
// 3. Extract: indices 0, 1, 2, 3 (exclusive of 4) → "Java"
275275
```
276276

277277
### Understanding Unicode and Multi-byte Characters
@@ -285,8 +285,8 @@ console.log(ascii.slice(0, 2)); // "He" (works as expected)
285285

286286
// Example 2: Emojis (often 2 code units = 1 character)
287287
const emoji = "Hello 😀 World";
288-
console.log(emoji.length); // 13 (not 12! 😀 counts as 2)
289-
console.log(emoji.slice(0, 7)); // "Hello 😀" (7 code units = 6 chars + emoji)
288+
console.log(emoji.length); // 14 (not 12! 😀 counts as 2, and there are 2 spaces)
289+
console.log(emoji.slice(0, 8)); // "Hello 😀" (8 code units = 6 chars + emoji)
290290

291291
// Example 3: Splitting surrogate pairs (demonstrating the problem)
292292
const unicode = "A\u{1D4AF}B"; // Mathematical script T
@@ -301,7 +301,7 @@ console.log(unicode.slice(0, 3)); // "A𝒯" (correct)
301301
- If you need to split by actual characters, consider using `Array.from(str)` or the spread operator `[...str]`
302302
- For most practical purposes, the standard methods work fine with ASCII and common Unicode text
303303

304-
## Understanding substring() / String.prototype.substring()
304+
## Understanding `substring()` / `String.prototype.substring()`
305305

306306
The `String.prototype.substring()` method (commonly called `substring()`) returns a part of the string between the start and end indexes, or to the end of the string. Unlike `slice()`, `substring()` has some quirky behaviors that can lead to unexpected results, making it less intuitive for many developers. `substring()` was one of the earliest string methods in JavaScript (since ES1) and has legacy behaviors that were kept for backward compatibility.
307307

@@ -313,19 +313,19 @@ string.substring(startIndex, endIndex)
313313

314314
### Parameters
315315

316-
- **startIndex**: The zero-based index at which to begin extraction. If negative, NaN, or undefined, it's treated as 0. If greater than `string.length`, it's treated as `string.length`.
317-
- **endIndex** (optional): The zero-based index before which to end extraction (exclusive). If negative, NaN, or undefined, it's treated as 0. If omitted, defaults to `string.length`. If greater than `string.length`, it's treated as `string.length`.
316+
- **`startIndex`**: The zero-based index at which to begin extraction. If undefined, negative, or NaN, it's treated as 0. If greater than `string.length`, it's treated as `string.length`.
317+
- **`endIndex`** (optional): The zero-based index **before which** to end extraction (exclusive). If omitted, defaults to `string.length`. If undefined, negative, or NaN, it's treated as 0. If greater than `string.length`, it's treated as `string.length`.
318318

319319
### Internal Algorithm
320320

321321
The `substring()` method processes indices differently from `slice()`:
322322

323-
1. **Convert startIndex**:
323+
1. **Convert `startIndex`**:
324324
- If negative, NaN, or undefined: convert to 0
325325
- If greater than `string.length`: convert to `string.length`
326326
- Otherwise: use as-is
327327

328-
2. **Convert endIndex**:
328+
2. **Convert `endIndex`**:
329329
- If omitted: use `string.length`
330330
- If negative, NaN, or undefined: convert to 0
331331
- If greater than `string.length`: convert to `string.length`

0 commit comments

Comments
 (0)