substring()
ES3+Returns the part of the string between the start and end indexes.
Syntax
string.substring(indexStart, indexEnd)Parameters
indexStart number Index of the first character to include
indexEnd number optionalIndex of the first character to exclude
Return Value
A new string containing the specified part
Examples
const str = 'JavaScript';
console.log(str.substring(0, 4));
console.log(str.substring(4)); 📌 When to Use
Use substring() when you need to extract a portion of a string and you have positive start and end indices. It is useful when the indices might be swapped accidentally, as substring() will automatically reorder them.
⚠️ Common Mistakes
Using substring() when you need negative index support - substring() treats negative values as 0, unlike slice() which counts from the end.
Confusing substring() with substr() (deprecated) - substr() uses length as the second parameter, not end index.
Not realizing that substring() swaps arguments if start > end, which can mask bugs in your logic.
✅ Best Practices
Prefer slice() over substring() in modern code for its more intuitive negative index handling and consistent behavior.
Use substring() only when you specifically need the argument swapping behavior or are maintaining legacy code.
When extracting from a known start position to the end, omit the second parameter: str.substring(5) instead of str.substring(5, str.length).
⚡ Performance Notes
substring() and slice() have virtually identical performance characteristics in modern JavaScript engines. The choice between them should be based on code clarity and the specific features needed (like negative indices), not performance considerations.
🌍 Real World Example
Text Selection and Highlighting
substring() is commonly used in text editors and search functionality where you need to extract and highlight portions of text based on selection ranges or search results.
// Highlight search term in text
function highlightText(text, searchTerm) {
const index = text.toLowerCase().indexOf(searchTerm.toLowerCase());
if (index === -1) return text;
const before = text.substring(0, index);
const match = text.substring(index, index + searchTerm.length);
const after = text.substring(index + searchTerm.length);
return before + '<mark>' + match + '</mark>' + after;
}
const text = 'Welcome to JavaScript programming';
console.log(highlightText(text, 'JavaScript'));
// Output: 'Welcome to <mark>JavaScript</mark> programming'
// Extract text between selection indices
function getSelectedText(text, selectionStart, selectionEnd) {
// substring automatically handles if start > end
return text.substring(selectionStart, selectionEnd);
}
console.log(getSelectedText('Hello World', 0, 5)); // 'Hello'
console.log(getSelectedText('Hello World', 5, 0)); // 'Hello' (swapped)