There are many articles on the Internet about the differences between substr, substring and slice methods, and the contents of the articles are basically the same. Then, I moved the code in one of the articles to a local computer for testing, and found that the test results were somewhat different from the original article.
I believe more in the code I have personally verified, and then write it down for future reference.
substr
document.write("|" str.substr(0,5) "|" "
");
document.write("|" str.substr(0) "|" "< ;br />");
document.write("|" str.substr(5,1) "|" "
");
document.write("|" str .substr(-5,2) "|" "
");
document.write("|" str.substr(-2,-5) "|" "
Print effect
|12345|
|123456|
|6|
IE: |12| Chrome: |23|
substring
document.write("|" str.substring(0,5) "|" "
");
document.write("|" str.substring(0) "|" "
");
document.write("|" str.substring(5,1) "|" "
");
document.write("| " str.substring(-5,2) "|" "
");
document.write("|" str.substring(-2,-5) "|" "
");
document.write("|" str.substring(2,-5) "|" "
");
Print effect
|12345|
|123456|
|2345|
|12|
|12|
slice
document.write("|" str.slice(0,5) "|" "< ;br />");
document.write("|" str.slice(0) "|" "
");
document.write("|" str.slice (5,1) "|" "
");
document.write("|" str.slice(-5,2) "|" "
");
document.write("|" str.slice(-2,-5) "|" "
");
document.write("|" str.slice(2,- 5) "|" "
");
Print effect
|12345|
|123456|
|2|
||
If the result you expected is exactly the same as the printing effect, then your basic skills must be good. If you are a little hesitant or the result is beyond your expectation, then my article is somewhat useful.
Summary
substr
The arg2 of this method and the arg2 of the other two methods simply represent different meanings, so they are extracted separately.
When arg1<0, the results of different browsers are different. IE directly changes arg1 to 0, and Chrome's subscript reading method is changed from reading from left to right to reading from right to left
substring and slice
(1) arg2 > arg1, that is, when parameter 2 is greater than parameter 1
substring: automatically reverse the position, the larger value is at the arg2 position, and the smaller value is at the arg1 position
slice: returns a null character String
(2) Processing of negative numbers
substring: Convert the parameter with negative value to 0
slice: Convert the parameter with negative value into (string length-parameter numerical value)