Overview
In the past, the substr() method was used in JavaScript to extract a string by specifying a “starting position” and a “length.” However, substr() is now deprecated. This means it is outdated and might be removed from web standards in the future. This article explains how to use the recommended slice() method to safely and modernly implement the logic of “getting X characters starting from index Y.”
Specifications (Input/Output)
- Input: Long text, a starting index, and the number of characters to retrieve.
- Output: A substring of the specified length.
- Operation: * Users specify numbers in an input form.
- Clicking a button displays the extraction result.
- The logic replicates the “length specification” behavior of
substrusingslice.
Basic Usage
To replicate length-based extraction, you pass “starting position + desired length” as the second argument to slice(start, end).
const text = "Professional";
const start = 3;
const length = 5;
// Modern way to get the same result as substr(3, 5)
// From index 3, up to (but not including) index 3 + 5
const result = text.slice(start, start + length);
console.log(result); // "fessi"
Full Code (HTML / JavaScript)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Extraction Tool</title>
<style>
body { font-family: sans-serif; padding: 20px; max-width: 600px; }
.control-group { margin-bottom: 15px; }
label { display: inline-block; width: 100px; font-weight: bold; }
input[type="number"] { width: 80px; padding: 5px; }
textarea { width: 100%; height: 80px; padding: 5px; box-sizing: border-box; }
button { padding: 8px 16px; background: #007bff; color: white; border: none; cursor: pointer; }
button:hover { background: #0056b3; }
.result-box {
margin-top: 20px;
padding: 15px;
background: #e9ecef;
border-left: 5px solid #007bff;
font-family: monospace;
font-size: 1.2em;
}
</style>
</head>
<body>
<h2>String Extraction Tool (By Length)</h2>
<div class="control-group">
<p>Target Text:</p>
<textarea id="targetText">The quick brown fox jumps over the lazy dog.</textarea>
</div>
<div class="control-group">
<label for="startIndex">Start Index:</label>
<input type="number" id="startIndex" value="4" min="0">
<span>(index)</span>
</div>
<div class="control-group">
<label for="lengthVal">Length:</label>
<input type="number" id="lengthVal" value="5" min="0">
<span>characters</span>
</div>
<button id="extractBtn">Run Extraction</button>
<div id="resultOutput" class="result-box">Results will appear here</div>
<script src="app.js"></script>
</body>
</html>
JavaScript
/**
* References to HTML elements
*/
const targetText = document.getElementById("targetText");
const startIndex = document.getElementById("startIndex");
const lengthVal = document.getElementById("lengthVal");
const extractBtn = document.getElementById("extractBtn");
const resultOutput = document.getElementById("resultOutput");
/**
* Helper function to extract string by length
* (Alternative implementation for String.prototype.substr)
* @param {string} str - Target string
* @param {number} from - Starting index
* @param {number} len - Number of characters to get
* @returns {string} - Extracted string
*/
const extractByLength = (str, from, len) => {
// End position of slice = start position + length
return str.slice(from, from + len);
};
/**
* Click event handler for the extraction button
*/
const handleExtract = () => {
const text = targetText.value;
const start = parseInt(startIndex.value, 10) || 0;
const length = parseInt(lengthVal.value, 10) || 0;
// Execute extraction
const result = extractByLength(text, start, length);
// Display result
resultOutput.textContent = result;
console.log(`Start: ${start}, Length: ${length}, Result: "${result}"`);
};
// Register event listener
extractBtn.addEventListener("click", handleExtract);
Customization Tips
- Handling Negative Values: In
substr, a negative first argument meant “counting from the end.”slicealso supports negative values. However, if you use negative values, the length calculation logic (start + length) needs adjustment depending on your specific goal. - Safe Character Limits: If the specified length exceeds the end of the string,
sliceautomatically stops at the end. It is safe and does not cause errors.
Important Notes
- Deprecation of
substr: While you might seesubstr(from, length)in legacy systems, do not use it for new projects. Official documentation like MDN warns that it may be removed from web standards. - Surrogate Pairs (Emojis): Both
sliceandsubstrcount based on “UTF-16 code units,” not actual characters. If you cut a 4-byte character like an emoji (e.g., 🍎) in the middle, it will break. For strict character counting, use the spread syntax:[...str].slice(start, end).join('').
Advanced Applications
Extracting by Length from the End
This example shows how to get “2 characters starting from the 5th character from the end.”
const text = "1234567890";
// Identify position 5 from the end and get 2 characters
const start = -5;
const len = 2;
// slice(-5, -5 + 2) => slice(-5, -3)
const result = text.slice(start, start + length);
console.log(result); // "67"
Conclusion
To extract a string by “length,” use the expression slice(start, start + length). This replicates the behavior of the deprecated substr method using a modern, standard approach. Always be mindful of whether your method arguments represent an “index (position)” or a “count (quantity).”
