Extract substring from string without regex using javascript string.substring()
method; In this tutorial, you will learn all about JavaScript string.substring()
method and how to extract a substring from a string using this method.
JavaScript string.substring()
method
The JavaScript string.substring()
method returns the new sub string from a given string, the basis of the provided index.
The following syntax demonstrates substring()
method:
str.substring(indexA [, indexB])
The string.substring()
method takes 2 parameters: indexA
and indexB
:
- The
indexA
is a position where to start the extraction. - The
indexB
is a position where to end the extraction.
Remember some important things about substring()
method:
- If you ignore the
indexB
, thesubstring()
returns the substring to the end of the string. - If
indexA
equalsindexB
, thesubstring()
method returns an empty string. - If
indexA
is greater than theindexB
, thesubstring()
swaps their roles: theindexA
becomes theindexB
. - If either
indexA
orindexB
is less than zero or greater than thestring.length
, thesubstring()
considers it as zero (0). - If any parameter is
NaN
, thesubstring()
treats it as if it were zero (0).
Examples: JavaScript substring()
method
Let’s take look at some examples of string.substring()
js string method.
1) Extracting a substring from the starting of the string
Extract a substring from the between two indexes of provided string, and return a new substring.
See the following example:
let string = 'Hello, Programmer'; let substring = string.substring(0,4); console.log(substring);
Output:
Hello
2) Extracting a substring to the end of the string
The following example uses the javascript string.substring() to extract at position 6, and return a new sub string.
See the following example:
let string = 'Hello, Programmer'; let substring = string.substring(6); console.log(substring);
Output:
Programmer
Conclusion
In this tutorial, you have learned all about JavaScript string.substring()
method.