C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript String slice() MethodThe JavaScript string slice() method is used to fetch the part of the string and returns the new string. It required to specify the index number as the start and end parameters to fetch the part of the string. The index starts from 0. This method allows us to pass a negative number as an index. In such case, the method starts fetching from the end of the string. It doesn't make any change in the original string. SyntaxThe slice() method is represented by the following syntax: string.slice(start,end) Parameterstart - It represents the position of the string from where the fetching starts. end - It is optional. It represents the position up to which the string fetches. In other words, the end parameter is not included. ReturnPart of the string JavaScript String slice() Method ExampleLet's see some simple examples of slice() method. Example 1Here, we will print the part of the string by passing starting and ending index. <script> var str = "TheDeveloperBlog"; document.writeln(str.slice(2,5)); </script> Output: vat Example 2Here, we will provide starting index only. In such case, the method fetches the string up to its length. <script> var str = "TheDeveloperBlog"; document.writeln(str.slice(0)); </script> Output: TheDeveloperBlog Example 3This is one more example where we provide only the starting index. <script> var str = "TheDeveloperBlog"; document.writeln(str.slice(4)); </script> Output: tpoint Example 4In this example, we will provide negative number as an index. In such case, the method starts fetching from the end of the string. <script> var str = "TheDeveloperBlog"; document.writeln(str.slice(-5)); </script> Output: point Example 5In this example, we will provide negative number as a starting and ending index. In such case, the method starts fetching from the end of the string. var str = "TheDeveloperBlog"; document.writeln(str.slice(-5,-1)); Output: poin
Next TopicJavaScript String
|