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

随声附和 提交于 2019-12-18 22:35:00

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

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

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

Notes on substring():

  • 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():

  • 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()

推荐做法:优先使用slice方法

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!