JavaScript is an essential programming language in web development. In particular, string manipulation is frequently used for formatting data, analysis, and dynamically updating the UI. In this article, we will explain three commonly used JavaScript string methods—substr, substring, and slice—in detail. Since these methods provide similar functionality, understanding their differences will help you choose the right one for each situation. We will also discuss why substr has been deprecated and provide alternative approaches, offering practical advice for writing JavaScript using modern best practices.
2. Basic Information and Usage of Each Method
This section explains the basic syntax and usage of substr, substring, and slice. Understanding these methods will help you choose the appropriate one and improve code readability and maintainability.
2.1 substr Method
Syntax:
string.substr(start, length)
Description:
start: Specifies the starting index for extraction (0-based).
length: Specifies the number of characters to extract. If omitted, extraction continues to the end of the string.
Note: The substr method is deprecated, and it is recommended to avoid using it in future code. Use slice or substring instead. Alternative Example (using slice):
Supports negative values: Negative indices count from the end of the string.
Works for both strings and arrays: It can also extract elements from arrays, making it highly versatile.
3. Comparison Table of Each Method
Method
Start Position
End Position
Negative Values
Recommendation Level
substr
Required
Length-based
×
Deprecated
substring
Required
Required
×
High
slice
Required
Required
○
Highly Recommended
Choosing the Right Method by Use Case:
Extracting short segments: → slice
When negative values are needed: → slice
Legacy code compatibility: → Avoid substr; migrate as needed
4. Practical Code Examples
Basic String Manipulation
let text = "JavaScriptProgramming";
// Extract the first 10 characters
console.log(text.slice(0, 10)); // "JavaScript"
// Extract the last 3 characters
console.log(text.slice(-3)); // "ing"
Extracting Values Based on a Pattern
let url = "https://example.com/index.html";
// Get the file name
console.log(url.slice(url.lastIndexOf("/") + 1)); // "index.html"
5. How to Handle Deprecated Methods
JavaScript’s substr method is deprecated. This is because substr has been classified as a non-recommended method in the latest ECMAScript specifications.
This section explains the issues with substr, alternative methods, and how to migrate your code.
5.1 Why Is substr Deprecated?
Poor readability:
substr uses the second argument as the “number of characters to extract,”
which differs from other methods that use an end index.
This inconsistency makes the code harder to understand.
Potential future compatibility issues due to spec changes:
Older features are deprecated during ECMAScript standardization.
New code should not rely on them.
No support for negative values:
substr does not support negative indices, while slice does.
let url = "https://example.com/index.html";
// Deprecated code
let filename = url.substr(url.lastIndexOf("/") + 1);
console.log(filename); // "index.html"
// Recommended (slice)
let filenameNew = url.slice(url.lastIndexOf("/") + 1);
console.log(filenameNew); // "index.html"
5.3 Refactoring Points for Legacy Code
Perform a code scan:
Use tools like ESLint to detect where substr is used.
Strengthen test coverage:
Use unit tests to ensure behavior remains correct after replacing methods.
Migrate gradually:
Prioritize replacement in important or frequently executed sections.
5.4 Benefits of Migrating Away from substr
Improved readability and maintainability:
The intent of the code becomes clearer, improving team understanding.
Compatibility with modern standards:
Following ECMAScript standards ensures long-term stability.
Flexible support for negative values:
slice enables concise extraction from both start and end positions.
6. Frequently Asked Questions (FAQ)
This section summarizes common questions and answers about JavaScript string manipulation methods.
Q1: Can I still use substr?
A: Yes, most modern browsers still support substr.
However, since ECMAScript marks it as deprecated, it should be avoided in new projects or codebases requiring future compatibility. Recommended alternative:
let str = "JavaScript";
console.log(str.slice(0, 4)); // "Java"
Q2: What is the difference between slice and substring?
Q3: What are the risks of continuing to use deprecated methods?
A:
Potential browser support removal:substr may eventually be unsupported.
Increased maintenance costs: Debugging deprecated features takes additional time.
Lower code quality: Failing to follow modern standards reduces readability.
Q4: Which method is best for long strings?
A:slice is best because it supports negative indices and offers strong flexibility. Example:
let longText = "This is a very long text string used for testing purposes.";
// First 10 characters
console.log(longText.slice(0, 10)); // "This is a "
// Last 10 characters
console.log(longText.slice(-10)); // "purposes."
Q5: How can I count backward using negative values?
A: Use slice, as substring treats negative values as 0. Example:
A: Modern browsers show no major performance differences among slice, substring, or substr.
Since all are native functions, prioritize readability and maintainability over micro-optimizations.
7. Summary and Recommended Best Practices
In this article, we explored the JavaScript string methods substr, substring, and slice, covering their basic syntax, differences, practical code examples, and migration strategies for deprecated methods. This section reorganizes the key characteristics of each method and presents recommended modern best practices.
7.1 Summary of Each Method
Method Name
Main Characteristics
Recommendation Level
substr
Specifies start index and length; does not support negative values. Deprecated.
Not Recommended
substring
Specifies start and end indices; negative values become 0. Suitable for simple use cases.
Recommended
slice
Specifies start and end indices; supports negative values. Very flexible and versatile.
Highly Recommended
7.2 Practical Selection Criteria
Use substring for simple range extraction:
Best when negative values are not needed. Example:
let str = "JavaScript";
console.log(str.substring(0, 4)); // Output: "Java"
Use slice for maximum flexibility:
Supports negative indices and is the preferred method for new code. Example:
let str = "JavaScript";
console.log(str.slice(-6)); // Output: "Script"
Replace substr as soon as possible:
Migrate to slice or substring when maintaining legacy code.
7.3 Modern Best Practices
Write code with readability in mind:
Clear and concise code improves long-term maintainability.
Avoid deprecated methods:
substr may lose browser support in future updates—migrate early.
Use slice when working with negative values:
slice is the only method that handles negative indices correctly.
Use ESLint and test suites to maintain code quality:
Static analysis helps detect deprecated methods and enforce modern coding styles.
7.4 Example of a Modern Coding Style
// Example: Extract domain from an email address
let email = "user@example.com";
let domain = email.slice(email.indexOf("@") + 1);
console.log(domain); // Output: "example.com"
// Example: Get file extension from a URL
let url = "document.pdf";
let extension = url.slice(-3);
console.log(extension); // Output: "pdf"
7.5 Action Plan for Readers
Review your existing code:
Check if substr is used in your project and replace it where necessary.
Follow best practices in new code:
Use modern, flexible patterns and avoid deprecated features.
Leverage comments and community questions:
Share questions or use cases to help others learn while strengthening your understanding.
Conclusion
This article provided an in-depth explanation of JavaScript’s substr, substring, and slice methods, including syntax, examples, comparison tables, and migration strategies.
Avoid substr because it is deprecated.
Use substring for simple scenarios.
Use slice for maximum flexibility and modern best practices.
Use these insights to write efficient, maintainable JavaScript code.
8. Related Links and References
To deepen your understanding of substr, substring, and slice, here are helpful links and references.
Official documentation and learning resources will help you keep up with the latest JavaScript updates and techniques.
Overview: A Japanese Q&A site ideal for asking technical questions in native language.
Conclusion
This section introduced a wide range of resources—from official references to tutorials, sample code repositories, and community platforms—to support ongoing learning about JavaScript string operations. Key Takeaways:
Check official documentation regularly:
Ensure your coding style stays aligned with the latest standards.
Strengthen skills through hands-on coding:
Practice makes concepts clearer and improves real-world application.
Engage with the community:
Sharing questions and solutions helps deepen understanding and broaden your network.