String.slice和String.substring有什么区别? [英] What is the difference between String.slice and String.substring?

查看:138
本文介绍了String.slice和String.substring有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道这两种方法之间的区别:

Does anyone know what the difference is between these two methods:

String.protorype.slice
String.protorype.substring


推荐答案

slice( )的作用类似于 substring(),但有一些不同的行为。

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

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

他们有什么共同点:


  1. 如果开始等于停止:返回一个空字符串

  2. 如果省略 stop :将字符提取到字符串的末尾

  3. 如果任一参数大于字符串的长度,将使用字符串的长度。

  1. If start equals stop: returns an empty string
  2. If stop is omitted: extracts characters to the end of the string
  3. If either argument is greater than the string's length, the string's length will be used instead.

区别 substring()


  1. 如果开始>停止,然后 substring 将交换这两个参数。

  2. 如果任一参数为负数或 NaN ,它被视为 0

  1. If start > stop, then substring will swap those 2 arguments.
  2. If either argument is negative or is NaN, it is treated as if it were 0.

区分 slice()


  1. 如果开始>停止 slice()将返回空字符串。 (

  2. 如果开始为否定:设置来自的字符串的结尾,与Firefox中的 substr()完全相同。在Firefox和IE中都会出现此行为。

  3. 如果 stop 为负:将stop设置为: string .length - Math.abs(停止)(原始值),但限制为0(因此, Math.max(0,string.length + stop) ECMA中涵盖的$ c>)规范。

  1. If start > stop, slice() will return the empty string. ("")
  2. If start is negative: sets char from the end of string, exactly like substr() in Firefox. This behavior is observed in both Firefox and IE.
  3. If stop is negative: sets stop to: string.length – Math.abs(stop) (original value), except bounded at 0 (thus, Math.max(0, string.length + stop)) as covered in the ECMA specification.

资料来源:编程的基本艺术&开发:Javascript:substr()v.s. substring()

这篇关于String.slice和String.substring有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆