Skip to content

Commit 00cac2d

Browse files
delete: interview questions & migration guide
1 parent 3192d65 commit 00cac2d

File tree

1 file changed

+1
-151
lines changed

1 file changed

+1
-151
lines changed

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

Lines changed: 1 addition & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,6 @@ This comprehensive guide will provide an in-depth exploration of each method, co
2828
- **Type coercion behavior** and how non-number values are handled
2929
- **Unicode and special character handling** for international strings
3030
- **Integration patterns** with other JavaScript string methods
31-
- **Migration strategies** for legacy codebases
32-
- **Interview preparation** with common questions and answers
3331

3432
By the end of this article, you'll not only understand each method's behavior but also gain the expertise to choose the right method for your specific use case, write more robust code, and debug string manipulation issues effectively.
3533

@@ -693,7 +691,7 @@ string.substr(startIndex, length)
693691
- **Not Part of ECMAScript Standard**: Though widely supported, it's not part of the official JavaScript specification
694692
- **Can Be Replaced**: All use cases can be handled with `slice()` instead
695693

696-
**Recommendation**: Use `slice()` instead of `substr()` in all cases. See migration examples in the section below.
694+
**Recommendation**: Use `slice()` instead of `substr()` in all cases.
697695

698696
### `substr()` Examples
699697

@@ -1153,154 +1151,6 @@ console.timeEnd('substring');
11531151
// Choose based on functionality, not performance
11541152
```
11551153

1156-
## Migration Guide: Replacing substr() and substring()
1157-
1158-
If you have existing code using `substr()` or `substring()`, here's how to migrate to `slice()`:
1159-
1160-
### Replacing substr()
1161-
1162-
```javascript
1163-
// OLD: Using substr()
1164-
const result1 = str.substr(start, length);
1165-
1166-
// NEW: Using slice()
1167-
const result1 = str.slice(start, start + length);
1168-
1169-
// OLD: Using substr() with negative start
1170-
const result2 = str.substr(-n);
1171-
1172-
// NEW: Using slice() with negative index
1173-
const result2 = str.slice(-n);
1174-
1175-
// OLD: Using substr() with negative start and length
1176-
const result3 = str.substr(-6, 3);
1177-
1178-
// NEW: Using slice() - calculate start index
1179-
const startIndex = str.length + (-6); // or use Math.max(0, str.length - 6)
1180-
const result3 = str.slice(startIndex, startIndex + 3);
1181-
```
1182-
1183-
### Replacing substring()
1184-
1185-
```javascript
1186-
// OLD: Using substring() (works the same when start < end)
1187-
const result1 = str.substring(start, end);
1188-
1189-
// NEW: Using slice() (drop-in replacement)
1190-
const result1 = str.slice(start, end);
1191-
1192-
// OLD: Using substring() with swapped arguments (common mistake)
1193-
const result2 = str.substring(end, start); // This swaps automatically!
1194-
1195-
// NEW: Using slice() - be explicit about what you want
1196-
const result2 = str.slice(Math.min(start, end), Math.max(start, end));
1197-
// OR if you really want swapping behavior:
1198-
const result2 = start > end ? str.slice(end, start) : str.slice(start, end);
1199-
```
1200-
1201-
### Common Interview Questions and Answers
1202-
1203-
Here are typical interview questions about these methods:
1204-
1205-
#### Question 1: What's the difference between slice() and substring()?
1206-
1207-
**Answer:**
1208-
- `slice()` supports negative indices (counts from end), `substring()` treats negatives as 0
1209-
- `slice()` returns empty string if start > end, `substring()` swaps the arguments
1210-
- `slice()` is more modern and recommended, `substring()` is legacy but still supported
1211-
- `slice()` behavior is consistent with `Array.slice()`
1212-
1213-
#### Question 2: How would you get the last 3 characters of a string?
1214-
1215-
**Answer:**
1216-
```javascript
1217-
// Method 1: Using slice() with negative index (RECOMMENDED)
1218-
const last3 = str.slice(-3);
1219-
1220-
// Method 2: Using slice() with calculated index
1221-
const last3 = str.slice(str.length - 3);
1222-
1223-
// Method 3: Using substring() (less intuitive)
1224-
const last3 = str.substring(str.length - 3);
1225-
1226-
// Method 4: Using substr() (deprecated, don't use)
1227-
const last3 = str.substr(-3); // DON'T USE
1228-
```
1229-
1230-
#### Question 3: What happens when you call substring(5, 2)?
1231-
1232-
**Answer:**
1233-
The arguments are automatically swapped, so `substring(5, 2)` becomes `substring(2, 5)`. This returns the substring from index 2 to index 4 (exclusive of 5).
1234-
1235-
In contrast, `slice(5, 2)` would return an empty string because `slice()` doesn't swap arguments.
1236-
1237-
### Working with Template Literals and Dynamic Strings
1238-
1239-
```javascript
1240-
// Extracting from template literals
1241-
const name = "John Doe";
1242-
const age = 30;
1243-
const template = `Hello, ${name}! You are ${age} years old.`;
1244-
1245-
// Extract name from template
1246-
const nameStart = template.indexOf(name);
1247-
const extractedName = template.slice(nameStart, nameStart + name.length);
1248-
console.log(extractedName); // "John Doe"
1249-
1250-
// Extracting dynamic portions
1251-
function extractVariable(template, variable) {
1252-
const start = template.indexOf(variable);
1253-
if (start === -1) return null;
1254-
return template.slice(start, start + variable.length);
1255-
}
1256-
```
1257-
1258-
### Error Handling and Validation Patterns
1259-
1260-
```javascript
1261-
// Robust extraction function with validation
1262-
function safeExtract(str, start, end, method = 'slice') {
1263-
// Input validation
1264-
if (typeof str !== 'string') {
1265-
throw new TypeError('First argument must be a string');
1266-
}
1267-
1268-
if (str.length === 0) {
1269-
return '';
1270-
}
1271-
1272-
// Validate indices
1273-
const startNum = Number(start);
1274-
const endNum = end !== undefined ? Number(end) : undefined;
1275-
1276-
if (isNaN(startNum)) {
1277-
throw new TypeError('Start index must be a number');
1278-
}
1279-
1280-
if (end !== undefined && isNaN(endNum)) {
1281-
throw new TypeError('End index must be a number');
1282-
}
1283-
1284-
// Choose method
1285-
switch (method) {
1286-
case 'slice':
1287-
return str.slice(startNum, endNum);
1288-
case 'substring':
1289-
return str.substring(startNum, endNum);
1290-
default:
1291-
throw new Error(`Unknown method: ${method}`);
1292-
}
1293-
}
1294-
1295-
// Usage with error handling
1296-
try {
1297-
const result = safeExtract("Hello World", 0, 5, 'slice');
1298-
console.log(result); // "Hello"
1299-
} catch (error) {
1300-
console.error('Extraction error:', error.message);
1301-
}
1302-
```
1303-
13041154
## Browser Compatibility
13051155

13061156
All three methods are widely supported:

0 commit comments

Comments
 (0)