- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Substring: Extracting Portions of Strings
The substring()
method in JavaScript extracts a portion of a string and returns it as a new string without modifying the original string.
How to Use substring() in JavaScript
The substring()
method takes two parameters: the start index and the end index (optional). The extraction includes characters from the start index up to, but not including, the end index.
string.substring(startIndex, endIndex)
string
: The string from which to extract the substring.startIndex
: The position where the extraction begins (inclusive).endIndex
: Optional. The position where the extraction ends (exclusive). If omitted, the extraction continues to the end of the string.
Examples:
let text = "Hello, World!";
let part = text.substring(1, 5);
console.log(part); // Outputs: "ello"
let fromStart = text.substring(7);
console.log(fromStart); // Outputs: "World!"
Handling Negative Indices
Unlike some other JavaScript methods, such as slice()
, the substring()
method does not support negative indices. If you pass a negative value as the startIndex
or endIndex
, substring()
will treat it as 0
.
let text = "Hello, World!";
console.log(text.substring(-3, 5)); // Outputs: "Hello"
The negative value -3
is treated as 0
, so the method extracts the substring starting from the beginning of the string.
Behavior When startIndex
is Greater than endIndex
If the startIndex
is greater than the endIndex
, the substring()
method automatically swaps the two values. This ensures that the substring is always extracted correctly, regardless of the parameter order.
let text = "Hello, World!";
console.log(text.substring(7, 2)); // Outputs: "llo, "
The method treats substring(7, 2)
as substring(2, 7)
and extracts characters from index 2
to 6
.
When to Use substring() in JavaScript
The substring()
method is useful for extracting parts of a string based on specific conditions or requirements.
Extracting a Fixed Portion
You can extract fixed portions of a string, such as substrings that always occupy the same length and position.
let str = "AB1234CD";
let letters = str.substring(0, 2);
let numbers = str.substring(2, 6);
console.log(letters); // Outputs: "AB"
console.log(numbers); // Outputs: "1234"
Extracting Variable Portions
You might need to extract variable portions of strings based on dynamically determined indexes.
let text = "Welcome to JavaScript!";
let firstWord = text.substring(0, text.indexOf(' '));
console.log(firstWord); // Outputs: "Welcome"
Processing User Input
Substrings can be handy when you need to process parts of user input, such as form data or structured text.
let phoneNumber = "(123) 456-7890";
let areaCode = phoneNumber.substring(1, 4);
console.log(areaCode); // Outputs: "123"
Examples of Using substring() in JavaScript
Many real-world applications utilize substring()
to manipulate and process string data efficiently.
Extracting the First Character
The substring()
method can help extract the first character of a string.
const greeting = "Hello!";
const firstChar = greeting.substring(0, 1);
console.log(firstChar); // Outputs: "H"
Email Domain Extraction
Web applications may need to extract the domain part of an email address for validation or verification purposes.
let email = "user@example.com";
let domain = email.substring(email.indexOf('@') + 1);
console.log(domain); // Outputs: "example.com"
Generating Preview Text
Content management systems might use substring()
to generate summary or preview text by truncating content.
let articleContent = "JavaScript is a versatile programming language that powers the web.";
let preview = articleContent.substring(0, 30) + "...";
console.log(preview); // Outputs: "JavaScript is a versatile prog..."
URL Path Extraction
Analytics tools can use substring()
to extract specific parts of URLs for tracking and reporting.
let url = "<https://www.example.com/user/profile/settings>";
let path = url.substring(url.indexOf('.com/') + 5);
console.log(path); // Outputs: "user/profile/settings"
Removing Empty Strings
You can also handle and check for an empty string when working with substring()
.
const text = "";
if (text.substring(0, 1) === "") {
console.log("This is an empty string.");
}
Learn More About JavaScript Substring
What is a Substring in JavaScript?
A substring in JavaScript is a contiguous sequence of characters within a string. The substring()
method provides a simple way to extract this sequence.
Another common method for extracting substrings is the slice()
method, which works similarly but can accept negative indices.
let text = "Hello, World!";
let part = text.slice(1, 5);
console.log(part); // Outputs: "ello"
JavaScript String Contains Substring
To check if a string contains a substring, you can use the includes()
method.
let sentence = "JavaScript is awesome!";
let contains = sentence.includes("awesome");
console.log(contains); // Outputs: true
Find Substring in JavaScript
The indexOf()
method can help locate the position of a substring within a string. It returns the index of the first occurrence, or -1
if not found.
let sentence = "Find the position of a substring.";
let position = sentence.indexOf("position");
console.log(position); // Outputs: 10
JavaScript Trim Substring
Before extracting a substring, you may want to trim whitespace from the original string using trim()
.
let text = " Trim me ";
let trimmed = text.trim();
let part = trimmed.substring(0, 4);
console.log(part); // Outputs: "Trim"
Using Regular Expressions for Substrings
While substring()
is straightforward, a regular expression can provide more advanced matching and extraction capabilities.
const text = "The price is $5.99.";
const priceMatch = text.match(/\$\d+\.\d{2}/);
console.log(priceMatch[0]); // Outputs: "$5.99"
Performance Considerations
For large-scale string operations, consider the performance implications of using substring()
. While efficient for most use cases, heavy or nested string manipulations may require optimized approaches.
const bigString = "A".repeat(1000000);
console.time("substring");
const segment = bigString.substring(500000, 500010);
console.timeEnd("substring"); // Outputs the time taken
Integration with Front-End Development
In front-end projects, substring()
is frequently used to manipulate and display text dynamically, often alongside CSS for styling.
const title = "JavaScript Tutorial";
const shortTitle = title.substring(0, 10);
document.querySelector(".title").textContent = shortTitle + "...";
Using Substring in APIs
The substring()
method is also essential when working with data from an API. For example, parsing strings from API responses to extract meaningful data.
const apiResponse = "USER_12345_ACTIVE";
const userId = apiResponse.substring(5, 10);
console.log(userId); // Outputs: "12345"
Method Returns a New String
The substring()
method returns a new string while leaving the original string unmodified, which is ideal for non-destructive string manipulations.
const str = "Learn JavaScript!";
const newStr = str.substring(6);
console.log(newStr); // Outputs: "JavaScript!"
console.log(str); // Outputs: "Learn JavaScript!" (unchanged)
String.prototype and substring
The substring()
method is part of string.prototype, meaning it’s available on every JavaScript string object.
const text = "Prototype";
console.log(String.prototype.substring === text.substring); // Outputs: true
Comparison with the slice()
Method
The substring()
and slice()
methods are similar but have key differences:
-
Negative Indices:
substring()
treats negative indices as0
.slice()
supports negative indices, counting from the end of the string.
javascript CopyEdit let text = "Hello, World!"; console.log(text.substring(-5, 8)); // Outputs: "Hello, W" console.log(text.slice(-5, 8)); // Outputs: ""
-
Parameter Order:
substring()
swaps thestartIndex
andendIndex
ifstartIndex
is greater.slice()
does not swap the indices.
javascript CopyEdit let text = "Hello, World!"; console.log(text.substring(8, 3)); // Outputs: "lo, W" console.log(text.slice(8, 3)); // Outputs: ""
When to Use Each Method:
- Use
substring()
for straightforward substring extraction where you do not need negative indices. - Use
slice()
when you need support for negative indices or when you prefer more precise control over parameter behavior.
Using substring()
is a powerful way to handle text processing tasks in JavaScript. By understanding its syntax and applications, you can effectively manage string data in your projects.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.