Home >Web Front-end >JS Tutorial >About the difference between substring() and substr() (detailed tutorial)
Below I will share with you an example based on the use and difference between substring() and substr(). It has a good reference value and I hope it will be helpful to everyone.
In JavaScript, interception is usually used. The so-called interception is actually to obtain the content from a certain position to a certain position of the intercepted element. Then JS provides me with the two substring and substr Method:
What is the difference between these two interception methods? Direct code demonstration:
substring(a,b):
a: indicates the starting position
b: Indicates the end position
! But it is worth noting: when intercepting, the intercepted content includes the element at the starting position, but does not include the element at the ending position!
Example:
function sub1(){ var str = 'javascript'; return str.substring(0,4); } console.log(sub1()); //返回值为‘java' function sub2(){ var str = 'javascript'; return str.substring(1,4); } console.log(sub2()); //返回值为‘ava'
Summary: When substring is intercepted, the starting position is included and the ending position is not included, and Both parameters a and b are positional values, that is, index values
substr (index, length):
index: Represents the starting position
length: Represents the length of the intercepted content
! The element at the starting position is included when intercepting!
Example:
function sub3(){ var str = 'javascript'; return str.substr(0,4); } console.log(sub3()); //返回值为‘java' function sub4(){ var str = 'javascript'; return str.substr(1,4); } console.log(sub4()); //返回值为‘avas'
Summary: When substr is intercepted, including the starting position, the two parameters are starting Starting position and interception length
! Pay attention to the distinction and use it wisely!
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement the streamlined style in Vue (detailed tutorial)
How to customize global components in vue?
How to implement multi-page development in vue2.0
How to implement the drag verification code function using jQuery and vue
Detailed introduction to several JavaScript coding specifications (detailed tutorial)
The above is the detailed content of About the difference between substring() and substr() (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!