Slice method in JavaScript | Used Slice the String and Array

The JavaScript slice method is used for extracts parts of a string and returns the extracted parts in a new string or selected elements in an array.

How to javascript remove part of String?

For removing a part of the string in JS you have to use the slice method.

JavaScript String slice() method

You have to pass the start and end parameter value in the slice() method. A slice method will return the extracted parts in a new string. Where a first character has position will be 0 and the second has position 1, and so on.

If you want string from the end then use negative number values.

Let’s see a simple example. In the string, we are slice the string from 0 to 5 character and showing it’s in an alert box.

Output:

JavaScript String slice method

Q: How to Extract the whole string in JS?

Answer: use the slice method with 0 value. See the below example for it.

JavaScript Array slice() Method

Javascript array slice() method extracts a section of an array and returns a new array. This method selects the elements starting at the given start parameter, and ends at, but does not include the given end parameter.

Syntax:

Example

Output:

JavaScript Array slice Method

Note: The original array will not be changed.

Do comment if you have any doubts and questions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.