Home >Web Front-end >JS Tutorial >A brief discussion on the difference between substr and substring in Javascript_javascript skills

A brief discussion on the difference between substr and substring in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:37:361090browse

Since there is a need to intercept strings in the project, I used the substr automatically prompted by the IDE. I didn’t think much about it and thought there was not much difference between substr and substring.

But it’s not, just listen to me.

1. substr(index, length)

Extracts the specified number of characters from the string from the starting index number.

The substr method can pass in two parameters index and length. Index is the starting bit, and length is the intercepted length.

When index is a non-negative integer:

a. If no parameters are passed in, the string itself will be obtained.

For example: "abcdefg".substr() -> "abcdefg"

b. If only one parameter is passed in, namely index, the last digit of the string will be intercepted by default.

For example: "abcdefg".substr(2) -> "defg".

When index is a negative integer:

c. If a negative integer subscript is passed in, counting from back to front, the starting bit is 1, and when reaching the subscript of the absolute value of the negative integer, interception is from front to back.

For example: "abcdefg".substr(-2) -> "fg" <=> "abcdefg".substr(-2 "abcdefg".length)

2. substring(start, end)

Extracts the characters between two specified subscripts in the string.

substring also passes in two parameters, but these two parameters are subscript numbers. The subscript is calculated from 0, and the intercepted length is the difference between the two subscripts

Can be recorded as "Including head but not tail"

Such as: "abcdefg".substring(2,4) -> "cd"

Statement:
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