JavaScript String Methods Explained: substr vs substring vs slice (Best Practices & Modern Usage)

1. Introduction

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.
Example Usage:
let str = "JavaScript";
console.log(str.substr(0, 4)); // Output: "Java"
console.log(str.substr(4, 6)); // Output: "Script"
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):
let str = "JavaScript";
console.log(str.slice(0, 4)); // Output: "Java"
console.log(str.slice(4));   // Output: "Script"

2.2 substring Method

Syntax:
string.substring(start, end)
Description:
  • start: Start index of the extraction.
  • end: End index (character at this index is not included).
Example Usage:
let str = "JavaScript";
console.log(str.substring(0, 4)); // Output: "Java"
console.log(str.substring(4, 10)); // Output: "Script"
Points:
  1. Argument order is automatically corrected: If you call substring(10, 4), it will be treated as substring(4, 10).
  2. Negative values are ignored: Any negative argument is treated as 0.
Alternative example when negative values are needed (using slice):
let str = "JavaScript";
console.log(str.slice(-6)); // Output: "Script"

2.3 slice Method

Syntax:
string.slice(start, end)
Description:
  • start: Start index of the extraction.
  • end: End index (character at this index is not included).
Example Usage:
let str = "JavaScript";
console.log(str.slice(0, 4));  // Output: "Java"
console.log(str.slice(-6));   // Output: "Script"
Points:
  1. Supports negative values: Negative indices count from the end of the string.
  2. Works for both strings and arrays: It can also extract elements from arrays, making it highly versatile.

3. Comparison Table of Each Method

MethodStart PositionEnd PositionNegative ValuesRecommendation Level
substrRequiredLength-based×Deprecated
substringRequiredRequired×High
sliceRequiredRequiredHighly 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?

  1. 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.
  1. Potential future compatibility issues due to spec changes:
  • Older features are deprecated during ECMAScript standardization. New code should not rely on them.
  1. No support for negative values:
  • substr does not support negative indices, while slice does.

5.2 How to Migrate to Modern Methods

Case 1: Extracting a Fixed-Length Substring

// Deprecated code
let str = "JavaScript";
console.log(str.substr(0, 4)); // "Java"

// Recommended (slice)
console.log(str.slice(0, 4)); // "Java"

Case 2: Extracting the End of a String

// Deprecated code
console.log(str.substr(-6)); // Error (negative not supported)

// Recommended (slice)
console.log(str.slice(-6)); // "Script"

Case 3: Extracting Part of a URL or Filename

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

  1. Perform a code scan:
  • Use tools like ESLint to detect where substr is used.
  1. Strengthen test coverage:
  • Use unit tests to ensure behavior remains correct after replacing methods.
  1. Migrate gradually:
  • Prioritize replacement in important or frequently executed sections.

5.4 Benefits of Migrating Away from substr

  1. Improved readability and maintainability:
  • The intent of the code becomes clearer, improving team understanding.
  1. Compatibility with modern standards:
  • Following ECMAScript standards ensures long-term stability.
  1. 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?

A: The table below summarizes their differences:
Featureslicesubstring
End index behaviorEnd index is excludedEnd index is excluded
Negative valuesSupportedTreated as 0
FlexibilityHighModerate
RecommendationHighly recommendedRecommended
Examples:
let str = "JavaScript";

// slice examples
console.log(str.slice(0, 4));   // "Java"
console.log(str.slice(-6));    // "Script"

// substring examples
console.log(str.substring(0, 4));  // "Java"
console.log(str.substring(4, 10)); // "Script"

Q3: What are the risks of continuing to use deprecated methods?

A:
  1. Potential browser support removal: substr may eventually be unsupported.
  2. Increased maintenance costs: Debugging deprecated features takes additional time.
  3. 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:
let str = "JavaScript";

// slice supports negative values
console.log(str.slice(-6));  // "Script"

// substring treats negative as 0
console.log(str.substring(-6)); // "JavaScript"

Q6: Are there performance differences?

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 NameMain CharacteristicsRecommendation Level
substrSpecifies start index and length; does not support negative values. Deprecated.Not Recommended
substringSpecifies start and end indices; negative values become 0. Suitable for simple use cases.Recommended
sliceSpecifies start and end indices; supports negative values. Very flexible and versatile.Highly Recommended

7.2 Practical Selection Criteria

  1. 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"
  1. 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"
  1. Replace substr as soon as possible:
  • Migrate to slice or substring when maintaining legacy code.

7.3 Modern Best Practices

  1. Write code with readability in mind:
  • Clear and concise code improves long-term maintainability.
  1. Avoid deprecated methods:
  • substr may lose browser support in future updates—migrate early.
  1. Use slice when working with negative values:
  • slice is the only method that handles negative indices correctly.
  1. 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

  1. Review your existing code:
  • Check if substr is used in your project and replace it where necessary.
  1. Follow best practices in new code:
  • Use modern, flexible patterns and avoid deprecated features.
  1. 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.

8.1 Official Documentation

  1. MDN Web Docs – JavaScript String Object
  • Link: String – MDN Web Docs
  • Overview: A complete reference for JavaScript’s String object with detailed specifications and examples.
  1. ECMAScript Specification (ECMA-262)
  • Link: ECMAScript Official Specification
  • Overview: The official language specification covering the latest ECMAScript features, deprecated methods, and technical details.

8.2 Learning Sites and Tutorials

  1. JavaScript.info – String Manipulation Guide
  • Link: JavaScript.info
  • Overview: An extensive guide covering both basic and advanced string operations with practical examples.
  1. Progate – JavaScript Beginner to Intermediate Course
  • Link: Progate
  • Overview: An interactive platform ideal for beginners learning through practical coding exercises.
  1. DotInstall – JavaScript Introductory Lessons
  • Link: DotInstall
  • Overview: Short video lessons that make it easy to learn JavaScript visually and quickly.

8.3 Practical Sample Code Resources

  1. GitHub – JavaScript Sample Projects
  • Link: GitHub
  • Overview: Learn best practices and real-world patterns by exploring open-source projects.
  1. CodePen – Interactive Code Sharing
  • Link: CodePen
  • Overview: Share and test your code with other developers or browse examples for inspiration.

8.4 Recommended Books

  1. JavaScript: The Definitive Guide (7th Edition)
  • Overview: A comprehensive, authoritative reference covering JavaScript from fundamentals to advanced features.
  1. Mastering Modern JavaScript – Revised Edition
  • Overview: A practical reference focusing on modern JavaScript and up-to-date coding standards.

8.5 Community and Forums

  1. Stack Overflow (Japanese)
  • Link: Stack Overflow
  • Overview: A Q&A community where you can troubleshoot JavaScript problems efficiently.
  1. Qiita
  • Link: Qiita
  • Overview: A Japanese platform rich with practical articles and JavaScript case studies.
  1. Teratail
  • Link: Teratail
  • 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:
  1. Check official documentation regularly:
  • Ensure your coding style stays aligned with the latest standards.
  1. Strengthen skills through hands-on coding:
  • Practice makes concepts clearer and improves real-world application.
  1. Engage with the community:
  • Sharing questions and solutions helps deepen understanding and broaden your network.
広告