Latest

recent

JavaScript slice() method

Definition and Usage

The slice() method extracts a part of a string and returns the extracted part in a new string.

Syntax

stringObject.slice(start,end)

Parameter Description
start Required. Specify where to start the selection. Must be a number. Starts at 0
end Optional. Specify where to end the selection. Must be a number


Tips and Notes

Tip: You can use negative index numbers to select from the end of the string.
Note: If end is not specified, slice() selects all characters from the specified start position and to the end of the string.

Example 1

In this example we will extract all characters from a string, starting at position 0:

<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(0));
</script>

The output of the code above will be:

Hello happy world!


Example 2

In this example we will extract all characters from a string, starting at position 6:

<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(6));
</script>

The output of the code above will be:

happy world!


Example 3

In this example we will extract only the first character from a string:

<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(0,1));
</script>

The output of the code above will be:

H


Example 4

In this example we will extract all the characters from position 6 to position 11:

<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(6,11));
</script>

The output of the code above will be:

happy
JavaScript slice() method Reviewed by 1000sourcecodes on 21:01 Rating: 5
Powered by Blogger.