How to use slice method in javascript

藏色散人
Release: 2023-01-07 11:42:46
Original
12469 people have browsed it

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)".

How to use slice method in javascript

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)
Copy after login

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:

Copy after login

Output:

happy world!
Copy after login

Example 2

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

Copy after login

Output:

happy
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!