JavaScript String slice() Method

You are Here:

JavaScript String slice() Method

The slice() method extracts a section of a string and returns it as a new string.

Note: This method does not alter the original string.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str = "Hello there my old friend"; var result = str.slice(2); document.write(result); </script> </body> </html>

Syntax

str.slice(start, end)

Parameter Values

ValueTypeExplanation
startRequiredSpecifies the starting point to begin the extraction.
If positive, the starting point is set from first character of this string.
If negative, the starting point is set from (str.length + your value).
i.e., if your value is -5, then the starting point is (str.length + (-5))
endoptionalSpecifies the ending point to end the extraction.
If omitted the default value is the length of the string.

Return Value

ValueExplanation
strReturns a new string containing the extracted section of the string.

str.slice(x, y) with Two Arguments

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str = "Hello there my old friend"; var result = str.slice(12, 18); document.write(result); </script> </body> </html>

str.slice(-x) with Negative Argument

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str = "Hello there my old friend"; var result = str.slice(-6); document.write(result); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author