Summary of js string interception methods (front end)

This article will introduce several common methods of intercepting strings with js, and the differences between them.

1. slice(start,end)

start: [Required] The start position of the interception (subscript starts from 0)
end: [Optional] The end position of the interception, and does not include the character at the end subscript position (the subscript starts from 0)

  • When end is not passed, it means that the last digit of the character string is intercepted
  • When start is a negative number, it indicates the position from the end of the string
  • The value of end must be greater than start to be valid
var str = “csdn.net”
str.slice(2)  // dn.net
str.slice(1,5)  // sdn.
str.slice(-2)  // et
str.slice(-4,-2)  // .n

2. substr(start,length)

start: [Required] The starting position of the interception (subscript starts from 0)
length: [Optional] [Integer] The length needs to be intercepted

  • When the length is not passed, it means that the last digit of the character string is intercepted
  • When start is a negative number, it means the position counted from the end of the string
var str = “csdn.net”
str.slice(2)  // dn.net
str.slice(1,5)  // sdn.n
str.slice(-2)  // et
str.slice(-4,3)  // .ne

3. substring(from, to)

from: [Required] [Non-negative integer] The subscript starts from 0
to: [Optional] [Non-negative integer] 1 more than the last character of the string to be extracted in the string Object

  • method is used to extract the characters between the two specified subscripts in the string, but not including the characters at the end
  • When to is not passed, it means that the last digit of the character string is intercepted
  • All negative numbers are treated as 0
var str = “csdn.net”
str.slice(2)  // dn.net
str.slice(1,5)  // sdn.
str.slice(-2)  // csdn.net 相当于 str.slice(0)
str.slice(-4,3)  // csd 相当于 str.slice(0,3)
str.slice(4,-3)  // csdn 相当于 str.slice(4,0)

Guess you like

Origin blog.csdn.net/weixin_44490021/article/details/129022993