Skip to content

Commit e3a53d6

Browse files
fix: common pitfalls
1 parent 1ca5f46 commit e3a53d6

1 file changed

Lines changed: 4 additions & 24 deletions

File tree

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

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,7 +1020,7 @@ console.log(stripHTML('Plain text without tags'));
10201020

10211021
## Common Pitfalls and Mistakes
10221022

1023-
### Pitfall 1: Confusing substring() with slice()
1023+
### Pitfall 1: Confusing `substring()` with `slice()`
10241024

10251025
```javascript
10261026
const str = "Hello World";
@@ -1035,7 +1035,7 @@ console.log(str.slice(5, 0)); // "" (empty string)
10351035
// Solution: Use slice() consistently to avoid confusion
10361036
```
10371037

1038-
### Pitfall 2: Using Negative Indices with substring()
1038+
### Pitfall 2: Using Negative Indices with `substring()`
10391039

10401040
```javascript
10411041
const str = "JavaScript"; // Length: 10
@@ -1049,7 +1049,7 @@ console.log(str.slice(-3)); // "ipt" (last 3 characters)
10491049
console.log(str.slice(-3, -1)); // "ip" (from -3 to -1)
10501050
```
10511051

1052-
### Pitfall 3: Using substr() with End Index Instead of Length
1052+
### Pitfall 3: Using `substr()` with End Index Instead of Length
10531053

10541054
```javascript
10551055
const str = "JavaScript";
@@ -1060,32 +1060,12 @@ console.log(str.slice(0, 4)); // "Java" (up to index 4, exclusive)
10601060

10611061
// This difference matters!
10621062
console.log(str.substr(4, 6)); // "Script" (6 characters from index 4)
1063-
console.log(str.slice(4, 10)); // "Script" (from index 4 to 10)
1063+
console.log(str.slice(4, 6)); // "Sc" (from index 4 to 6, exclusive)
10641064

10651065
// Solution: Remember substr's second param is LENGTH, not end index
10661066
// Better: Use slice() instead of substr()
10671067
```
10681068

1069-
### Pitfall 4: Not Handling Edge Cases
1070-
1071-
```javascript
1072-
function extractSubstring(str, start, end) {
1073-
// BAD: No validation
1074-
return str.substring(start, end);
1075-
1076-
// GOOD: Handle edge cases
1077-
if (start < 0) start = 0;
1078-
if (end > str.length) end = str.length;
1079-
if (start >= end) return '';
1080-
return str.slice(start, end);
1081-
}
1082-
1083-
// Or even better: use slice() which handles most edge cases gracefully
1084-
function extractSubstringSafe(str, start, end) {
1085-
return str.slice(Math.max(0, start), end);
1086-
}
1087-
```
1088-
10891069
## Performance Considerations
10901070

10911071
While all three methods have similar performance characteristics, `slice()` is generally preferred because:

0 commit comments

Comments
 (0)