When working with JavaScript, you may come across situations where you need to extract a portion of a string. JavaScript provides two methods, substr and substring, that can be used to achieve this. While both methods can be used to extract substrings from a string, there are some differences between them that you should be aware of.
substr
The substr method is used to extract a portion of a string starting from a specified index and extending for a given number of characters. It takes two parameters: the starting index and the length of the substring.
Here’s an example that demonstrates how to use the substr method:
const str = "Hello, World!";
const substring = str.substr(7, 5);
console.log(substring); // Output: World
In the above example, we start extracting the substring from index 7 and extract 5 characters. As a result, the output will be “World”.
substring
The substring method is used to extract a portion of a string between two specified indices. It takes two parameters: the starting index and the ending index (exclusive).
Here’s an example that demonstrates how to use the substring method:
const str = "Hello, World!";
const substring = str.substring(7, 12);
console.log(substring); // Output: World
In the above example, we start extracting the substring from index 7 and end at index 12 (exclusive). As a result, the output will be “World”.
Differences
While both substr and substring can be used to extract substrings, there are a few key differences:
- The second parameter of substr represents the length of the substring, while in substring it represents the ending index (exclusive).
- If the second parameter of substr is negative, it is treated as 0, whereas in substring, negative indices are treated as 0.
- If the first parameter of substr is negative, it is treated as str.length + start, whereas in substring, negative indices are treated as 0.
It’s important to keep these differences in mind when deciding which method to use in your JavaScript code.
Now that you understand the difference between substr and substring, you can choose the appropriate method based on your specific requirements. Happy coding!
Leave a Reply