Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
substring() in javascript select a part of the string and return a substring. In this article, we will learn to work with strings using the substring() method.
You will learn what is substring and learn to extract a substring from a string by applying different methods. We will discuss substring and several ways to extract a substring from a string
Hello Everyone. In the string Hello Everyone, The string Hello is a substring of Hello Everyone. Also, the string Everyone is a substring of the string Hello Everyone.Note: Remember that only the part of a continuous sequence of characters can be considered a substring
quedemy could be:'quedemy',
'que', 'demy',
'qu', 'ue', 'ed', 'em', 'my',
'q', 'u', 'e', 'd', 'e', 'm', 'y'We can use the following methods to extract substring in javascript: substring() method and slice() method. Let's discuss in details.
substring() Methodsubstring() method to get substrings from a given string.substring() method is: substring(indexStart, indexEnd)substring() method can accept two arguments as indexStart and indexEnd. Then, the substring() method returns a substring from the starting index to the ending index.substring() method includes character of start index and does not include character of last index.const exStr = 'E-learning'
// 1. Get substring from startIndex '0' to endIndex '6'
console.log(exStr.substring(0, 7)) // output: E-learn
// 2. Get substring from startIndex '3' to endIndex '6'
console.log(exStr.substring(3, 7)) // output: earnE-learning. We applied the substring() method to get the substring E-learn and earn.endIndex is optional parameter. If the value of endIndex is not specified, it extracts all characters till the end of the stringconst exStr = 'E-learning'
// get substring from startIndex '3' till the end
console.log(exStr.substring(3)) // output: earningNote:
indexStartwill be treated as 0, if value ofindexStartisundefined,NaN, or not specified. Therefore, the substring() method returns the whole string.const exStr = 'E-learning' console.log(exStr.substring(undefined)) // output: E-learning console.log(exStr.substring(NaN)) // output: E-learning console.log(exStr.substring()) // output: E-learning
- If value of
indexStartis equal to the value ofindexEnd,substring()method will return an empty string.const exStr = 'E-learning' console.log(exStr.substring(2, 2)) // output: ""
slice() Methodslice() is also a built-in method in javascript and returns a part of the stringslice() method is: slice(indexStart, indexEnd)const str = 'Crack Interviews'
// Return a substring from index 0 to index 4
console.log(str.slice(0, 5)) // output: Crack
// Return a substring from index 2 to index 3
console.log(str.slice(2, 4)) // output: ac