Skip to content

Slice method in JavaScript | Used Slice the String and Array

  • by

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.

<!DOCTYPE html> 
	<html> 
		<script> 

	    var str = "Hello world!";
		var sb = str.slice(0, 5);  
		alert(sb); 
	  
	</script> 

	<body> 

	</body> 
	</html> 

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.

<script> 
	var str = "Hello world!";
	var sb = str.slice(0);  
        alert(sb); 
</script> 

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:

array.slice( begin [,end] );

Example

<!DOCTYPE html> 
	<html> 
	<script> 

		var arr = ["John", "Alley", "King", "Tim", "Rock"];
         document.write("arr.slice( 0, 2) : " + arr.slice( 1, 2) ); 
         document.write("<br />arr.slice( 1, 3) : " + arr.slice( 1, 3) ); 
	  
	</script> 

	<body> 

	</body> 
	</html> 

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading