Javascript string substring() is a powerful function that extracts a portion of a string based on given index values. In this article, we’ll delve into the workings of the substring()
function and explore real-world use cases where it can prove invaluable.
Understanding the substring() Function
substring()
is a built-in JavaScript string manipulation method that allows you to extract a portion of a string based on given index values. The method returns a new string output containing characters from the original string starting at the given starting index and ending at the specified end index (or the end of the string, if the end index is not provided).
The syntax for the substring()
the method is as follows:
const subStringResult = string.substring(startIndex, endIndex);
Here’s a breakdown of the parameters:
string
: The original string from which you want to extract a substring.startIndex
: The index at which the extraction should start (inclusive).endIndex
: (Optional) The index at which the extraction should stop. If not provided, the extraction will continue until the end of the string.
Please note substring()
method doesn’t modify the original string; it returns a new string that contains the extracted substring.
Here are a few examples to illustrate the usage of the substring()
method:
const originalString = "Hello, world!";
const substring1 = originalString.substring(7); // Extracts "world!"
const substring2 = originalString.substring(0, 5); // Extracts "Hello"
const substring3 = originalString.substring(7, 12); // Extracts "world"
In these examples, substring1
extracts characters from index 7 to the end of the string, substring2
extracts characters from index 0 to index 4, and substring3
extracts characters from index 7 to index 11.
Substrings can take negative index numbers
The substring()
method in JavaScript can accept negative numbers as parameters for both the start and end indices. When you pass negative indices, they are counted from the end of the string. The last character of the string is at index -1, the second-to-last character is at index -2, and so on.
Here’s how negative indices work with the substring()
method:
const originalString = "Hello, world!";
const substring1 = originalString.substring(-6); // Equivalent to substring(0)
const substring2 = originalString.substring(-12, -7); // Equivalent to substring(0, 5)
const substring3 = originalString.substring(7, -1); // Equivalent to substring(7, 11)
In these examples:
substring1
is equivalent to usingsubstring(0)
because negative -6 becomes 0.substring2
is equivalent to usingsubstring(0, 5)
because negative -12 becomes 0 and negative -7 becomes 5.substring3
is equivalent to usingsubstring(7, 11)
because negative -1 becomes the index of the last character.
Negative indices can be particularly useful when you want to extract a substring from the end of a string without needing to calculate the exact index yourself. Just remember that using negative indices with the substring()
method is a convenient way to work with strings, allowing you to easily handle substrings from both the beginning and end of the string.
Real-World Use Cases
Extracting Domains from URLs
Imagine you’re building a web application that requires extracting domain names from a list of URLs. The substring()
function can come to the rescue. Here’s how:
const urls = [
"https://www.test.com/page1",
"https://blog.sample.com/article",
"https://api.data.org/data"
];
const domains = urls.map(url => {
const startIndex = url.indexOf("//") + 2;
const endIndex = url.indexOf("/", startIndex);
return url.substring(startIndex, endIndex);
});
console.log(domains); //[ 'www.test.com', 'blog.sample.com', 'api.data.org' ]
Formatting Usernames
When dealing with usernames, you might want to display only the first few characters, followed by an ellipsis. Let’s see how substring()
can help:
const username = "adventureSeeker123";
const formattedUsername = username.length > 10
? username.substring(0, 10) + "..."
: username;
console.log(formattedUsername);
Trimming Excess Text
In scenarios where you’re displaying dynamic content like comments, you may want to trim the text to a certain length and add a “Read More” link. Here’s how you could do it:
const comment = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
const maxDisplayLength = 30;
const trimmedComment = comment.length > maxDisplayLength
? comment.substring(0, maxDisplayLength) + "..."
: comment;
console.log(trimmedComment);
Working with Time Formats
Suppose you’re working on a time tracking application and need to extract hours and minutes from a time string. The substring()
function can be employed:
const timeString = "09:45";
const hours = parseInt(timeString.substring(0, 2));
const minutes = parseInt(timeString.substring(3));
console.log(`Hours: ${hours}, Minutes: ${minutes}`);
Extracting Metadata from Strings
Consider a scenario where you’re processing strings containing metadata in a specific format, such as “Title – Author.” You can use the substring()
function to extract individual components:
const metadataString = "JavaScript Substring - John Doe";
const separatorIndex = metadataString.indexOf(" - ");
if (separatorIndex !== -1) {
const title = metadataString.substring(0, separatorIndex);
const author = metadataString.substring(separatorIndex + 3);
console.log(`Title: ${title}, Author: ${author}`);
} else {
console.log("Invalid metadata format");
}
Manipulating File Paths
When working with file paths, you might need to extract the file name and its extension. Let’s see how substring()
can help:
const filePath = "/documents/reports/report1.pdf";
const fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
const fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
console.log(`File Name: ${fileName}, Extension: ${fileExtension}`);
Formatting Phone Numbers
In scenarios where you’re displaying phone numbers, you may want to format them consistently. The substring()
function can be used to rearrange digits:
const phoneNumber = "1234567890";
const formattedNumber = `(${phoneNumber.substring(0, 3)}) ${phoneNumber.substring(3, 6)}-${phoneNumber.substring(6)}`;
console.log(`Formatted Number: ${formattedNumber}`);
Dynamic Data Masking
If you’re handling sensitive information like credit card numbers, you might want to mask parts of the data. Here’s how substring()
can assist:
const creditCardNumber = "1234 5678 9012 3456";
const maskedNumber = creditCardNumber.substring(0, 12).replace(/\d/g, "*") + creditCardNumber.substring(12);
console.log(`Masked Number: ${maskedNumber}`);
Extracting Coordinates
If you’re working with geographical data in the form of coordinates, you can use the substring()
function to extract latitude and longitude:
const coordinates = "40.7128° N, 74.0060° W";
const latitude = parseFloat(coordinates.substring(0, coordinates.indexOf("°")));
const longitude = parseFloat(coordinates.substring(coordinates.indexOf(", ") + 2, coordinates.lastIndexOf("°")));
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
Reference
Conclusion
The JavaScript substring()
function continues to prove its versatility in various real-world scenarios. By creatively implementing it, developers can simplify complex tasks, enhance user experiences, and ensure consistent data presentation across their applications. Whether you’re working with URLs, formatting strings, or manipulating data, the substring()
function remains a valuable asset in your programming toolkit. Experiment with these examples and adapt them to your projects, taking full advantage of what this function has to offer. Happy coding!