JavaScript String.substring() Method
String extraction is one of the most common practice in programming. When it comes to JavaScript, this is not an exception. Luckily, JavaScript provides us with various ways of extracting substrings. One of these methods is the substring
method.
The String.prototype.substring()
method returns a new string that contains characters from the original string, starting from a specified index and ending before a second specified index.
In this tutorial, we will discuss how to use the substring()
method including the function syntax, parameters, return values, and examples of using this function.
Function Syntax
The syntax of substring()
method is as expressed below:
str.substring(indexStart[, indexEnd])
Where the parameters represent:
indexStart
- The position where to start the extraction. First character is at index 0.indexEnd
- The position where to end the extraction. This character will not be included.
Note: If indexStart
is greater than indexEnd
, the substring()
method will swap the two arguments; i.e. str.substring(1, 0)
is the same as str.substring(0, 1)
.
Function Example Usage
Example 1 - Basic usage
Let us demonstrate the function usage with a simple example:
let str = "Hello, World!";
let result = str.substring(0, 5);
console.log(result);
In this example, we extract the first five characters of the string.
The resulting output is as shown:
Hello
Example 2 - Without second argument
If we don’t provide the second argument, substring()
will extract characters till the end of the string as shown in the example below:
let str = "Hello, World!";
let result = str.substring(7);
console.log(result);
Output:
World!
Example 3 - Swapping arguments
In the beginning of the tutorial, we mentioned that if indexStart
is greater than indexEnd
, the method will swap these two values. Consider the example demonstration below:
let str = "Hello, World!";
let result = str.substring(5, 0);
console.log(result);
Result:
Hello
Example 4 - Using with other string methods
We can also use the substring()
method with other string methods.
For example, we can chain it with toUpperCase()
method:
let str = "Hello, World!";
let result = str.substring(7).toUpperCase();
console.log(result);
Output:s
WORLD!
NOTE: The substring()
method returns a new string and does not modify the original string.
Similarly, f the arguments are equal (indexStart == indexEnd
), substring()
returns an empty string.
Conclusion
That’s all about JavaScript substring()
method. Using this tutorial, you experienced how the function works and how to use in JavaScript programs.
However, pay attention to the positional indexes of the strings.