Many articles about the differences between substr, substring, and slice methods are found on the Internet, and the content is basically the same. Then, I moved the code in one of the articles to a local machine for testing and found that the test results were somewhat different from those in the original article.
I believe in the code I personally verified, and I will note it down for future reference.
Substr
Document. write ("|" + str. substr (0, 5) + "|" + "<br/> ");
Document. write ("|" + str. substr (0) + "|" + "<br/> ");
Document. write ("|" + str. substr (5, 1) + "|" + "<br/> ");
Document. write ("|" + str. substr (-5, 2) + "|" + "<br/> ");
Document. write ("|" + str. substr (-2,-5) + "|" + "<br/> ");
Print Effect
1 | 12345 | 2 | 123456 | 3 | 6 | 4 IE: | 12 | Chrome: | 23 | 5 | substring
Document. write ("|" + str. substring (0, 5) + "|" + "<br/> ");
Document. write ("|" + str. substring (0) + "|" + "<br/> ");
Document. write ("|" + str. substring (5, 1) + "|" + "<br/> ");
Document. write ("|" + str. substring (-5, 2) + "|" + "<br/> ");
Document. write ("|" + str. substring (-2,-5) + "|" + "<br/> ");
Document. write ("|" + str. substring (2,-5) + "|" + "<br/> ");
Print Effect
1 | 12345 | 2 | 123456 | 3 | 2345 | 4 | 12 | 5 | 6 | 12 | slice
Document. write ("|" + str. slice (0, 5) + "|" + "<br/> ");
Document. write ("|" + str. slice (0) + "|" + "<br/> ");
Document. write ("|" + str. slice (5, 1) + "|" + "<br/> ");
Document. write ("|" + str. slice (-5, 2) + "|" + "<br/> ");
Document. write ("|" + str. slice (-2,-5) + "|" + "<br/> ");
Document. write ("|" + str. slice (2,-5) + "|" + "<br/> ");
Print Effect
1 | 12345 | 2 | 123456 | 3 | 4 | 2 | 5 | 6 | if the expected result is exactly the same as the print result, your basic skills are not good. If you are somewhat hesitant or the results are unexpected, it will be helpful for me to write more articles.
Summary
Substr
The arg2 of this method and the arg2 of the other two methods have different meanings at all, so they are extracted separately.
When arg1 is <0, different browsers have different results. IE directly changes arg1 to 0, and Chrome subscript reads are changed from the original read from left to right to read from right to left.
Substring and slice
(1) arg2> arg1, that is, when parameter 2 is greater than parameter 1
Substring: automatically reverses the position. The value is greater than that of arg2, and the value is smaller than that of arg1.
Slice: returns an empty string.
(2) processing negative numbers
Substring: Convert the value of a negative number to 0.
Slice: convert a parameter with a negative value to (String Length-parameter value)