Home  >  Article  >  Web Front-end  >  What is the difference between String.slice and String.substring in js

What is the difference between String.slice and String.substring in js

coldplay.xixi
coldplay.xixiOriginal
2020-11-10 15:23:432515browse

The difference between String.slice and String.substring in js is: 1. If [start>stop], then substring will exchange these two parameters; 2. If [start>stop], slice will return a null character string.

What is the difference between String.slice and String.substring in js

The difference between String.slice and String.substring in js is:

slice() is similar to substring( ) , but has some different behavior.

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

What do they have in common:

  • If start equals stop: Return an empty string

  • If stop is omitted: extract characters to the end of the string

  • If either parameter is greater than the length of the string, the length of the string will be used instead.

substring() Difference:

  • If start > stop, then substring will exchange these two parameters.

  • If either argument is negative or NaN, it is treated as 0.

slice() Difference:

  • ##If start > stop, slice() will return an empty string. ( "" )

  • If start is negative: Sets char from the end of the string, just like substr() in Firefox. This behavior is observed in both Firefox and IE.

  • If stop is negative: set stop to: string.length – Math.abs(stop) (original value), but in range 0 in the ECMA specification (so, Math .max(0, string.length stop) ) is the limit.

Related free learning recommendations: JavaScript(Video)

The above is the detailed content of What is the difference between String.slice and String.substring in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn