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

相關文章
相關標籤/搜索