JavaScript字符串截取slice和substring的区别

slice() works like substring() with a few different behaviors.javascript

Syntax: string.slice(start, stop); Syntax: string.substring(start, stop); 

Notes on substring():java

  • If start equals stop, it returns an empty string.
  • If stop is omitted, it extracts characters to the end of the string.
  • If either argument is less than 0 or is NaN, it is treated as if it were 0.(小于0或NaN被当作0)
  • If either argument is greater than string’s length, either argument will use string’s length.
  • If start > stop, then substring will swap those 2 arguments.(若是stop大于start,则执行参数交换)

Notes on slice():less

  • If stop is omitted, slice extracted chars to the end of the string, exactly like substring().
  • If start > stop, slice() will NOT swap the 2 arguments.(返回空字符串)
  • If start is negative, slice() will set char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
  • If stop is negative, slice() will set stop to: (string.length – 1) – stop (original value).(stop为负数则stop+=string.length)

Source: Rudimentary Art of Programming & Development: Javascript: substr() v.s. substring()wordpress

推荐作法:优先使用slice方法spa

相关文章
相关标签/搜索