Home > Web Front-end > JS Tutorial > body text

js string interception function substr substring slice usage comparison_javascript skills

WBOY
Release: 2016-05-16 17:12:06
Original
1485 people have browsed it

There are three commonly used string interception functions: substr substring slice. The calling method is as follows:

Copy code The code is as follows:

stringObject.slice(start,end)
stringObject.substr(start,length)
stringObject.substring(start,end)

The most obvious one is substr, no. The two parameters are length, which is the interception length. The second parameter of the other two functions is the subscript of the last character (the character of the subscript is not included here, only the character before the character is intercepted)

Compared with slice and substring, slice subscript can be a negative number, such as -1 represents the last character, but substring cannot. If substring start is larger than end, then these two parameters will be exchanged before extracting the substring, but slice will not. Slice will return an empty string

Example:
Copy code The code is as follows:

var str="Helloworld"
console.log(str.substr(0, 2))
console.log(str.substring(2, 0))
console.log(str.substring(0, 2))
console.log(str.slice(0, -1))
console.log(str.slice(-1, 0))

Output:

He
He
He
Helloworl
( empty string)
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template