Skip to content

Commit 8653e78

Browse files
fix: Use Negative Indices with slice() for Cleaner Code
1 parent ce05d73 commit 8653e78

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

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

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,13 +1084,14 @@ const domainOld = email.substr(email.indexOf('@') + 1);
10841084

10851085
```javascript
10861086
// ✅ GOOD: Using negative indices with slice()
1087-
const lastChar = str.slice(-1); // Last character
1088-
const lastThree = str.slice(-3); // Last 3 characters
1089-
const allButLast = str.slice(0, -1); // All except last character
1087+
const lastChar = str.slice(-1); // Last character
1088+
const lastThree = str.slice(-3); // Last 3 characters
1089+
const allButLast = str.slice(0, -1); // All except last character
10901090

10911091
// ❌ AVOID: Calculating indices manually
1092-
const lastCharOld = str[str.length - 1]; // Less readable
1093-
const lastThreeOld = str.substring(str.length - 3); // More verbose
1092+
const lastCharOld = str.slice(str.length - 1); // Less readable, manual calculation
1093+
const lastThreeOld = str.slice(str.length - 3); // Less readable, manual calculation
1094+
const allButLastOld = str.slice(0, str.length - 1); // Less readable, manual calculation
10941095
```
10951096

10961097
### 3. Always Specify Both Parameters When Clarity Matters
@@ -1108,11 +1109,11 @@ const rest = str.slice(startIndex);
11081109
```javascript
11091110
// ✅ GOOD: Understand that end index is exclusive
11101111
const str = "Hello";
1111-
console.log(str.slice(0, 5)); // "Hello" (indices 0,1,2,3,4)
1112+
console.log(str.slice(0, 5)); // "Hello" (indices 0,1,2,3,4)
11121113
console.log(str.slice(0, str.length)); // "Hello" (all characters)
11131114

11141115
// Remember: end index is NOT inclusive!
1115-
console.log(str.slice(0, 4)); // "Hell" (not "Hello")
1116+
console.log(str.slice(0, 4)); // "Hell" (not "Hello")
11161117
```
11171118

11181119
### 5. Use Consistent Method Across Your Codebase

0 commit comments

Comments
 (0)