The subString () method and slice () method in the String class are described in section 2.8.4 of this book. The method and return result are basically the same, as shown in the following example:
Copy codeThe Code is as follows:
Var strObj = new String ("hello world ");
Alert (strObj. slice (3); // output: "ol world"
Alert (strObj. subString (3); // output: "ol world"
Alert (strObj. slice (3, 7); // output: "lo w"
Alert (strObj. subString (); // output: "lo w"
From the output results of the above code, we can see that the method called by the slice () method and subString () method are exactly the same as the output result, the two methods return the substrings of the strings to be processed. Each method accepts one or two parameters. The first parameter is the starting position of the substring to be obtained, the second parameter is to obtain the end position of the substring. If the second parameter is omitted, the default end position is the length of the String, and neither method changes the value of the String object.
Why are there two methods with identical functions? In fact, these two methods are not exactly the same, but they process parameters slightly differently only when the parameters are negative.
For negative parameters, the slice () method adds a parameter to the length of the string, and the subString () method treats it as 0, for example:
Copy codeThe Code is as follows:
Var strObj = new String ("hello world ");
Alert (strObj. slice (-3); // output: "rld"
Alert (strObj. subString (-3); // output: "hello world"
Alert (strObj. slice (3,-4); // output: "lo w"
Alert (strObj. subString (3,-4) // output the following result: "El"
In this way, we can see the main differences between slice () and subString () methods. If the parameter is only-3, slice () returns "rld", and subString () returns "hello world ". This is because for the string "hello world", slice (-3) will be converted to slice (8), and subString (-3) will be converted to subString (0 ). Similarly, the difference between 3 and-4 is obvious. The slice () method is converted to slice (), which is the same as the preceding example and returns "lo w ". The subString () method interprets the two parameters as subString (), which is actually subString (), because subString () always uses smaller parameters as the start bit, A large number is the most terminating digit.