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

1. Introduction

JavaScript is an essential programming language in modern web development. In particular, string manipulation is frequently used for data formatting, parsing, and dynamic UI updates.

This article provides a detailed explanation of three commonly used JavaScript string methods—substr, substring, and slice. Since these methods have similar functionality, understanding their differences will help you choose the most appropriate one for each situation.

We will also discuss why substr has been deprecated, introduce recommended alternatives, and provide practical advice to align your code with modern JavaScript best practices.

2. Basic Overview and Usage of Each Method

This section explains the basic syntax and usage of substr, substring, and slice in detail. By understanding each method, you can select the appropriate one and improve both code readability and maintainability.

2.1 substr Method

Syntax:

string.substr(start, length)

Description:

  • start: Specifies the starting position (index) for extraction. Indexing begins at 0.
  • length: Specifies the number of characters to extract. If omitted, characters are extracted from the start position to the end of the string.

Example:

let str = "JavaScript";
console.log(str.substr(0, 4)); // Output: "Java"
console.log(str.substr(4, 6)); // Output: "Script"

Important Notes:
The substr method is deprecated, and its use is discouraged in modern JavaScript development. Instead, use slice or substring as alternatives.

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: Specifies the starting position for extraction.
  • end: Specifies the ending position (the character at this index is not included).

Example:

let str = "JavaScript";
console.log(str.substring(0, 4));  // Output: "Java"
console.log(str.substring(4, 10)); // Output: "Script"

Key Points:

  1. Argument order is automatically adjusted: If substring(10, 4) is specified, it is automatically interpreted as substring(4, 10).
  2. Negative values are ignored: If a negative value is provided, it is treated as 0.

Alternative When Negative Values Are Required (Using slice):

let str = "JavaScript";
console.log(str.slice(-6)); // Output: "Script"

2.3 slice Method

Syntax:

string.slice(start, end)

Description:

  • start: Specifies the starting position for extraction.
  • end: Specifies the ending position (the character at this index is not included).

Example:

let str = "JavaScript";
console.log(str.slice(0, 4));  // Output: "Java"
console.log(str.slice(-6));   // Output: "Script"

Key Points:

  1. Supports negative values: Negative values are interpreted as offsets from the end of the string.
  2. Applicable to both strings and arrays: Since slice can also be used with arrays, it is a highly versatile method.

3. Comparison Table of Each Method

MethodStart PositionEnd PositionSupports Negative ValuesRecommendation
substrRequiredUses length×Deprecated
substringRequiredRequired×High
sliceRequiredRequiredMost Recommended

How to Choose by Use Case:

  • Extracting a short portion of a string:slice
  • When negative indexes are needed:slice
  • Legacy code compatibility: → Avoid substr and migrate to modern alternatives

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 a Value from a Specific Pattern

let url = "https://example.com/index.html";

// Get the filename
console.log(url.slice(url.lastIndexOf("/") + 1)); // "index.html"

5. Handling Deprecated Methods

In JavaScript, the substr method is considered deprecated. This is because it has been officially classified as a non-recommended approach in the latest ECMAScript specifications. This section explains the issues with substr, available alternatives, and practical migration strategies.

5.1 Why Is substr Deprecated?

  1. Low readability:
  • The substr method specifies the number of characters to extract as its second argument, which differs from other methods that use start and end positions. This inconsistency makes code harder to understand at a glance.
  1. Potential future compatibility issues due to specification changes:
  • During the ECMAScript standardization process, older features may be marked as deprecated. As a result, substr should be avoided in new code to ensure long-term compatibility.
  1. No support for negative values:
  • While substr does not support negative values, slice fully supports negative indexes, allowing more flexible string extraction.

5.2 How to Migrate to Alternative Methods

Case 1: Extracting a Fixed-Length Substring

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

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

Case 2: Extracting the End of a String

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

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

Case 3: Extracting a Portion of a URL or Filename

let url = "https://example.com/index.html";

// Deprecated code
let filename = url.substr(url.lastIndexOf("/") + 1);
console.log(filename); // Output: "index.html"

// Recommended code (slice)
let filenameNew = url.slice(url.lastIndexOf("/") + 1);
console.log(filenameNew); // Output: "index.html"

5.3 Refactoring Tips for Legacy Code

  1. Run a code scan:
  • Use tools such as ESLint to detect occurrences of substr in your codebase.
  1. Improve test coverage:
  • Use unit tests to verify behavior after refactoring and ensure that changes do not introduce regressions.
  1. Migrate gradually:
  • Prioritize critical sections of your codebase and replace deprecated methods step by step.

5.4 Benefits of Migrating Away from substr

  1. Improved readability and maintainability:
  • Code intent becomes clearer, making collaboration and long-term maintenance easier.
  1. Alignment with modern specifications:
  • Conforming to the ECMAScript standard ensures smoother future updates and compatibility.
  1. Flexible handling of negative values:
  • Using slice allows easy extraction from both the beginning and end of strings, resulting in cleaner and more concise code.

6. Frequently Asked Questions (FAQ)

This section summarizes common questions and answers related to JavaScript string manipulation methods, helping readers quickly resolve typical doubts.

Q1: Is substr still usable?

A:
Yes, substr still works in most modern browsers. However, since it is deprecated in the ECMAScript specification, it should be avoided in new projects or when considering long-term compatibility.

Recommended alternative:

let str = "JavaScript";
console.log(str.slice(0, 4)); // Output: "Java"

Q2: What is the difference between slice and substring?

A:
The table below summarizes the key differences between slice and substring.

Featureslicesubstring
End position handlingThe character at the specified position is not includedThe character at the specified position is not included
Negative valuesSupportedTreated as 0
FlexibilityHigh (supports backward indexing)Standard but less flexible
RecommendationMost recommendedHigh

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:
Continuing to use deprecated methods can lead to the following risks.

  1. End of browser support: In the future, substr may no longer be supported by browsers.
  2. Increased maintenance costs: Addressing bugs or warnings caused by deprecated methods can add unnecessary overhead.
  3. Decreased code quality: Failing to align with modern specifications reduces readability and maintainability.

Q4: Which method is best for handling long strings?

A:
When working with long strings, slice is the best choice due to its flexibility and support for negative indexes.

Example:

let longText = "This is a very long text string used for testing purposes.";

// Get the first 10 characters
console.log(longText.slice(0, 10)); // "This is a "

// Get the last 10 characters
console.log(longText.slice(-10));  // "purposes."

Q5: How can I count from the end using negative values?

A:
While slice supports negative values, substring treats negative values as 0, so caution is required.

Example:

let str = "JavaScript";

// Extract from the end using slice
console.log(str.slice(-6));  // "Script"

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

Q6: Are there any performance differences?

A:
In modern browsers, there are no significant performance differences between slice, substring, and substr. Since all are implemented as native functions, it is recommended to prioritize readability and maintainability over performance.

7. Summary and Recommended Best Practices

This article explained JavaScript string manipulation methods—substr, substring, and slice—from basic usage to key differences, practical examples, and strategies for handling deprecated methods.

This section summarizes each method and highlights recommended best practices based on modern JavaScript standards.

7.1 Summary of Each Method

MethodMain CharacteristicsRecommendation
substrSpecifies start position and length; does not support negative values. Deprecated.Deprecated
substringUses start and end positions; negative values are treated as 0. Suitable for simple use cases.Recommended
sliceUses start and end positions; supports negative values. Highly flexible and versatile.Most Recommended

7.2 Practical Criteria for Choosing the Right Method

  1. Use substring for simple range extraction:
  • Recommended when working with short strings and when negative values are not required. Example:
let str = "JavaScript";
console.log(str.substring(0, 4)); // Output: "Java"
  1. Choose slice for maximum flexibility:
  • Since it supports negative indexes and offers greater versatility, slice is the most recommended option for modern code. Example:
let str = "JavaScript";
console.log(str.slice(-6)); // Output: "Script"
  1. Replace substr as early as possible:
  • In legacy codebases, proactively replace substr with slice or substring.

7.3 Modern Best Practices

  1. Prioritize readability:
  • Writing clear and concise code improves long-term maintainability.
  1. Eliminate deprecated methods:
  • Since substr may be removed in future updates, actively migrate to slice or substring.
  1. Use slice when negative values are required:
  • slice provides flexible backward extraction, making it ideal for many real-world use cases.

7.4 Coding Style Examples

Finally, here are some examples of modern string manipulation written in a clean and maintainable coding style.

// Example: Extracting the domain from an email address
let email = "user@example.com";
let domain = email.slice(email.indexOf("@") + 1);
console.log(domain); // Output: "example.com"

// Example: Extracting a 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. Conduct a code review:
  • Check existing projects for usage of substr and replace it with slice or substring where appropriate.
  1. Apply best practices in new code:
  • Follow modern specifications and design code with readability and negative index handling in mind.
  1. Leverage comments and questions:
  • Encourage questions and discussions about unclear points or specific use cases to share knowledge within the community.

Conclusion

This article explained JavaScript string methods substr, substring, and slice using basic syntax, usage examples, and comparison tables.

  • substr should be avoided because it is deprecated.
  • substring is suitable for simple use cases.
  • slice is the most flexible and recommended method.

Use this knowledge to write efficient, readable, and maintainable JavaScript code.

8. Related Links and References

To further deepen your understanding of substr, substring, and slice, this section provides useful links and reference materials. Official documentation and learning resources will help you stay up to date with the latest specifications and advanced techniques.

8.1 Official Documentation

  1. MDN Web Docs – JavaScript String Object
  • Link: String – MDN Web Docs
  • Description: Official reference documentation for the JavaScript String object, including detailed specifications and examples for each method.
  1. ECMAScript Specification (ECMA-262)
  • Link: ECMAScript Official Specification
  • Description: The official ECMAScript specification detailing JavaScript language features, including deprecated methods and recent updates.

8.2 Learning Sites and Tutorials

  1. JavaScript.info – String Methods
  • Link: JavaScript.info
  • Description: Comprehensive explanations of string manipulation, from basics to advanced use cases, with practical examples.
  1. Progate – JavaScript Learning Courses
  • Link: Progate
  • Description: An interactive learning platform for beginners, covering JavaScript fundamentals through hands-on coding.
  1. Dotinstall – JavaScript Beginner Course
  • Link: Dotinstall
  • Description: A video-based learning platform that allows quick and visual understanding of JavaScript concepts.

8.3 Practical Sample Code Resources

  1. GitHub – JavaScript Sample Projects
  • Link: GitHub
  • Description: Learn real-world JavaScript patterns and best practices through open-source projects.
  1. CodePen – Interactive Code Playground
  • Link: CodePen
  • Description: A platform for sharing and experimenting with JavaScript code in real time.

8.4 Recommended Books

  1. JavaScript: The Definitive Guide, 7th Edition (O’Reilly)
  • Overview: A comprehensive reference covering JavaScript fundamentals through the latest language features.
  1. Modern JavaScript Development Guide (Revised Edition)
  • Overview: A practical guide focused on modern JavaScript syntax and real-world development techniques.

8.5 Communities and Forums

  1. Stack Overflow
  • Link: Stack Overflow
  • Description: A global Q&A community for programming-related questions and troubleshooting.
  1. Qiita
  • Link: Qiita
  • Description: A Japanese technical article platform featuring many practical JavaScript examples.
  1. Teratail
  • Link: Teratail
  • Description: A Japanese Q&A site where developers can ask questions in Japanese.

Summary

This section introduced official references, learning resources, sample code repositories, and developer communities related to JavaScript string manipulation.

Key Takeaways:

  1. Verify specifications using official documentation:
  • Make it a habit to check the latest specifications and usage guidelines.
  1. Strengthen practical skills through tutorials and sample code:
  • Hands-on coding reinforces both theoretical understanding and real-world application.
  1. Share knowledge through developer communities:
  • Engaging in discussions helps expand your expertise and professional network.
広告