In this article, we’ll explore the basics of these substring functions. Besides, we look at how it works and what its syntax is.
Furthermore, we study how it can be used in practical web development scenarios.
If we have a string “Hello World!”, we can use the substring function to extract the word “World.”
We can do this by specifying the substring’s starting and ending index positions.
- The starting index
- The ending index
The syntax is as follows:
In this syntax, the start parameter is the index position at which the substring begins. However, the end parameter is the index position at which the substring ends.
The End Parameter is Optional
It’s important to note that the end parameter is optional. If not provided, the substring function will extract all the characters from the start index position to the end of the string.
Here’s an example of how the substring function works:
let str = “Hello World!”;
let str = str.substring(6, 11);
console.log(substr); // Output: “World”
In this example, we create a string “Hello World!” and then use the substring function to extract the substring “World.”
The start parameter is 6. It is the index position of the letter “W” in the string. Besides, the end parameter is 11, which is the index position of the letter “d.”
If we omit the end parameter, the substring function will extract all the characters from the start index position to the end of the string:
let str = “Hello World!”;
let substr = str.substring(6);
console.log(substr); // Output: “World!”
In this example, we only provide the start parameter, 6. The substring function then extracts all the characters from the 6th index position to the end of the string.
Extracting part of a URL
When building web applications, extracting specific parts of a URL is often necessary.
For example, if we have a URL like “https://www.example.com/blog/article/1234”, we may want to extract the article ID (in this case, “1234”).
By using the substring function, we can easily extract the article ID from the URL:
let url = “https://www.example.com/blog/article/1234”;
let article = url.substring(URL.lastIndexOf(“/”) + 1);
console.log(article); // Output: “1234”
In this example, we use the lastIndexOf function to find the index position of the last forward slash in the URL.
We then add 1 to this index position to get the starting index position of the article ID. Finally, we use the substring function to extract the article ID from the URL.
The starting index is inclusive, and the ending index is exclusive. It means the character at the ending index is not included in the returned substring.
If the ending index is omitted, the substring will go to the end of the string. In addition, the substring method can be used to manipulate strings in various ways, such as:
- Removing or replacing particular character
- Extracting specific information from a string
- Formatting text in a desired way