![substring javascript substring javascript](https://media.geeksforgeeks.org/wp-content/uploads/20190310193641/1182.png)
It appears to be a less-robust version of the slice() method. I can't see a reason to use the substring() method. NOTE: According to W3Schools, using a negative index in substr() does not work with Internet Explorer (IE).
![substring javascript substring javascript](https://www.freecodecamp.org/news/content/images/2020/03/Ekran-Resmi-2020-03-22-15.54.09.png)
This can be especially useful if you know the length of the substring ahead of time and don't want to perform any superflous math to calculate the necessary indices. The substr() method can use a negative index but, rather than using a to-argument, it uses a length-argument. Should you try to use a negative index in substring(), it seems to be relative the beginning of the string (and therefore is out-of-bounds). When we run the above code, we get the following console output:Īs you can see, the slice() and substring() methods are roughly the same the only difference is that the slice() method can accept a negative index, relative to the end of the string. Let's start by using both start and length If the index is out of range, it returns the empty string. And with the negative, end-relevant index. What happens when we omit the last argument. What happens when we use two negative numbers. What happens when we start with a negative number. Let's start by using both begin and end. NOTE: We are starting at zero since Javascript is all
![substring javascript substring javascript](https://www.developerhelps.com/wp-content/uploads/2019/10/substring-javascript-min.jpg)
we can easily see where the indexes come into play with For these demos, let's create a numbered string so that Let's take a look as these three approaches in action: For both the slice() and substring() methods, the second argument is exclusive that is, the resultant substring will not contain the character at the final index. If it is not provided, the substring will consist of the start index all the way through the end of the string. In all cases, the second argument is optional. To clear up my own confusion and misconceptions, I wanted to take a quick look at the various ways in which Javascript allows for partial string extraction.įrom what I can see, there are three primary methods for substring extraction: When I think of slice(), I think of extracting portions of a Javascript array I don't think I was even aware that the Javascript String prototype had a slice() method. And, in his examples, Haverbeke makes frequent use of the String method, slice(). In the book, Eloquent Javascript: A Modern Introduction to Programming, Marijn Haverbeke takes the reader through a good number of string-parsing examples.