Syntax
string.substring(startIndex, endIndex)
- startIndex: The index where the substring starts (inclusive).
- endIndex (optional): The index where the substring ends (exclusive). If omitted, the substring will include all characters from the startIndex to the end of the string.
Parameters
- startIndex: This is the position where the substring starts. It is inclusive, meaning the character at this position is included in the returned substring. If the startIndex is greater than the string's length, an empty string is returned.
- endIndex: This parameter is optional. It indicates the position where the substring should stop, excluding the character at the endIndex. If you don't provide this parameter, the substring will go until the end of the string.
Return Value
The substring() method returns a new string containing the characters between the specified startIndex and endIndex. If startIndex is greater than endIndex, JavaScript swaps the values internally.
Examples
Extracting Substrings
To extract a portion of a string, you need to specify where to start and where to end the substring.
let text = "Hello, World!";
let result = text.substring(0, 5);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Hello
In the example above, the substring() method starts at index 0 (which is the letter "H") and ends at index 5, which excludes the space after "Hello".
Extracting Substrings by Character Index
If you know the character indices, you can use the substring() method to extract a specific portion of the string.
let text = "JavaScript is fun!";
let result = text.substring(11, 14);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
fun

You can also try this code with Online Javascript Compiler
Run Code
In this case, we extract the substring starting from index 11 (the letter "f") to index 14 (excluding the space after "fun").
Extracting a Portion of a URL
Suppose you want to extract the domain name from a URL. You can do that by specifying the starting and ending indices based on the position of "www." and ".com".
let url = "https://www.example.com";
let domain = url.substring(8, 19); // Starts at "w" and ends before "c"
console.log(domain);

You can also try this code with Online Javascript Compiler
Run Code
Output:
example

You can also try this code with Online Javascript Compiler
Run Code
Here, the substring starts at index 8 (right after "https://") and ends before index 19, extracting "example".
String Validation
You can also use substring() to check if a string contains a particular sequence of characters.
let text = "I love JavaScript";
if (text.substring(7, 17) === "JavaScript") {
console.log("Match found!");
} else {
console.log("No match.");
}

You can also try this code with Online Javascript Compiler
Run Code
This will check if the substring from index 7 to index 17 matches "JavaScript". The output will be:
Match found!
Removing a Prefix or Suffix
You can remove the prefix or suffix from a string by extracting only the relevant portion of the string.
let message = "Error: File not found";
let result = message.substring(7);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
File not found

You can also try this code with Online Javascript Compiler
Run Code
In this case, the substring starts at index 7, removing the "Error: " part of the string.
Handling Negative Indices
If you pass a negative index to the substring() method, it will be treated as 0. The substring() method does not allow negative indices to be used directly.
let text = "Hello, World!";
let result = text.substring(-5, -1);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Hello

You can also try this code with Online Javascript Compiler
Run Code
Here, the negative indices are treated as 0, so the substring starts at the beginning of the string and returns "Hello".
When the Starting Index is Greater
If the startIndex is greater than the endIndex, the method will swap the two values internally and still return the correct substring.
let text = "Coding Ninjas";
let result = text.substring(6, 3);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Nin

You can also try this code with Online Javascript Compiler
Run Code
In this example, even though the starting index is greater than the ending index, substring() internally swaps them, and we get the substring "Nin".
Using Only the Starting Index
If you provide only the startIndex and leave out the endIndex, the substring() method will return a substring starting from the startIndex to the end of the string.
let text = "Learn JavaScript";
let result = text.substring(6);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
JavaScript
Here, starting from index 6, the substring() method returns the rest of the string, which is "JavaScript".
Immutability
One important thing to note about the substring() method is that it does not modify the original string. Strings in JavaScript are immutable, which means once a string is created, it cannot be changed. Instead, methods like substring() return a new string containing the extracted characters.
let text = "Welcome!";
let result = text.substring(0, 3);
console.log(result);
console.log(text);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Wel
Welcome!
As you can see, the original string remains unchanged, and a new string "Wel" is returned.
Note: The concept of immutability is crucial when you are working with strings in JavaScript. If you need to modify a string, you'll have to create a new string with the desired changes instead of trying to alter the original one.
When to Use substring() in JavaScript
The substring() method is particularly handy in scenarios where you need to extract a specific portion of a string based on character positions. Let’s take a look at a few common use cases:
1. Extracting parts of a date or timestamp:
let dateString = "2023-05-18T09:30:00";
let year = dateString.substring(0, 4);
let month = dateString.substring(5, 7);
let day = dateString.substring(8, 10);
console.log(year); // Output: "2023"
console.log(month); // Output: "05"
console.log(day); // Output: "18"
2. Extracting a username from an email address:
let email = "kanika.arora@example.com";
let username = email.substring(0, email.indexOf("@"));
console.log(username); // Output: "kanika.arora"
3. Truncating long strings for display purposes:
let longText = "The concept of immutability is crucial when you are working...";
let truncatedText = longText.substring(0, 20) + "...";
console.log(truncatedText); // Output: "The concept of immut..."
These are just a few examples of how substring() can be used in real-world JavaScript applications. Whenever you need to extract a portion of a string based on character positions, substring() is a reliable and great option.
Frequently Asked Questions
What is the difference between substring() and slice() in JavaScript?
Both methods extract parts of a string, but slice() can handle negative indices, while substring() cannot.
What happens if the startIndex is greater than the endIndex in substring()?
The method swaps the two indices internally and extracts the substring between them, regardless of their order.
Can substring() modify the original string?
No, the substring() method does not modify the original string. It returns a new string.
Conclusion
In this article, we discussed how the substring() method in JavaScript can be used to extract portions of a string. We covered its syntax, parameters, and various use cases, including handling negative indices and scenarios where the starting index is greater than the ending index. This method is a useful tool for anyone working with strings in JavaScript and can help you manipulate strings effectively.