How to work Substring method in JavaScript
Posted By : Vinay Tiwari | 28-Dec-2017
In this blog, we will be learning about Substring method in javascript. 3 methods in javascript that can be used to recover a substring from a given string substring(),
substring() method: This method has 2 parameters namely start and end.The start parameter is a required one and defines the position from where to start the extraction.The end parameter is considered to be optional and defines the position where the extraction is expected to end. The character at the end position of the string is not included in the substring.
If the end parameter is not mentioned then all the characters from the starting position to the ending position of the string are extracted.
And if the value of the start parameter is more than the value of the end parameter, this method will swap the two arguments. Which means that the start value will be used as an end and end value will be used as the start.
Let's look at an
Extract the first 10 characters
var str = "JavaScript Blog"
var result = str.substring(0, 10);
console.log(result) // JavaScript
Here within this variable
If the value of the start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as a start.
var str = "JavaScript Blog"
var result = str.substring(10, 0);
console.log(result) // JavaScript
If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If the count is 0 or negative, an empty string is returned.
for
var str = "JavaScript Blog"
var result = str.substring(11);
console.log(result) // Blog
in this example, start parameter is 11 and count parameters are optional.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vinay Tiwari
Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.