Home > Article > Web Front-end > How to use slice method in javascript
The slice method in JavaScript can extract a certain part of a string and return the extracted part as a new string. Its usage syntax is such as "stringObject.slice(start,end)".
The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer
How to use the slice method in javascript?
The slice() method extracts a certain part of a string and returns the extracted part as a new string.
Syntax
stringObject.slice(start,end)
Parameters
start The starting index of the fragment to be extracted. If it is a negative number, this parameter specifies the position starting from the end of the string. That is, -1 refers to the last character of the string, -2 refers to the second to last character, and so on.
end The index immediately following the end of the segment to be extracted. If this parameter is not specified, the substring to be extracted includes the string from start to the end of the original string. If this parameter is negative, it specifies the position from the end of the string.
Return value
A new string. Includes all characters of the string stringObject from start (inclusive) to end (exclusive).
Description
The methods slice(), substring() and substr() (deprecated) of the String object can all return the specified part of the string. slice() is more flexible than substring() because it allows negative numbers as arguments. slice() differs from substr() in that it specifies a substring in terms of two character positions, whereas substr() specifies a substring in terms of character position and length.
Also note that String.slice() is similar to Array.slice().
Example
Example 1
In this example, we will extract all characters starting from position 6:
<script type="text/javascript"> var str="Hello happy world!" document.write(str.slice(6)) </script>
Output:
happy world!
Example 2
In this example, we will extract all characters from position 6 to position 11:
<script type="text/javascript"> var str="Hello happy world!" document.write(str.slice(6,11)) </script>
Output:
happy
Recommended learning:《javascript advanced tutorial》
The above is the detailed content of How to use slice method in javascript. For more information, please follow other related articles on the PHP Chinese website!