Home >Web Front-end >JS Tutorial >subString() method and slice() method of String class in javascript_javascript skills

subString() method and slice() method of String class in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:06:261260browse

Section 2.8.4 of the book talks about the subString() method and slice() method in the String class. Their usage and return results are basically the same, as shown in the following example:

Copy code The code is as follows:

var strObj = new String("hello world");
alert(strObj.slice(3)); / / Output result: "ol world"
alert(strObj.subString(3)); // Output result: "ol world"
alert(strObj.slice(3, 7)); // Output result: "lo w"
alert(strObj.subString(3,7)); // Output result: "lo w"

As can be seen from the output of the above code, slice( ) method and subString() method call method and output results are exactly the same. Both methods return substrings of the string to be processed, and both accept one or two parameters. The first parameter is the substring to be obtained. The starting position of the string. The second parameter is to obtain the ending position of the substring. If the second parameter is omitted, the ending position defaults to the length of the string, and neither method changes the value of the String object itself.

Why are there two methods with exactly the same function? In fact, the two methods are not exactly the same, but they handle parameters slightly differently only when the parameters are negative.

For negative parameters, the slice() method will add the length of the string to the parameter, and the subString() method will treat it as 0, for example:
Copy code The code is as follows:

var strObj = new String("hello world");
alert(strObj.slice(-3)); // Output result: "rld"
alert(strObj.subString(-3)); // Output result: "hello world"
alert(strObj.slice(3,-4)); // Output Result: "lo w"
alert(strObj.subString(3,-4)) // Output result: "hel"

In this way, you can see slice() and subString() The main difference in approach. When there is only parameter -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 using 3 and -4 is also obvious. The slice() method will be converted to slice(3,7), the same as the previous example, returning "low". The subString() method interprets these two parameters as subString(0,3), which is actually: subString(0,3), because subString() always uses the smaller parameter as the starting position, and the larger parameter The number is the final digit.
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