The job title is as follows:
----------------------------------------------------------------
The methods of string interception are slice (start,end+1), substring (start,end+1), substr (Start,n). There are some similarities or differences between them in terms of usage.
Slice (start,end+1): Two parameters, the parameter refers to the intercept position, the interception of the head with no tail; When a parameter is truncated, the end of the string is intercepted by default. The argument can be negative, and the negative number is inverted.
SUBSTRING (start,end+1): Two parameters, the parameter refers to the intercept position, the interception of the head with no tail; When a parameter is truncated, the end of the string is intercepted by default. The parameter cannot be a negative number.
SUBSTR (start,n): Two parameters, the first parameter refers to the intercept starting position, the second parameter refers to the number of intercepted characters; When a parameter is truncated to the end of the string by default, the first argument can be negative, and the second argument cannot be negative.
Write an example:
var str= "Today is Tuesday";
Console.log (Str.slice (3,6));//Intercept "Tuesday" and print
Console.log (str.substring (3,6));//Intercept "Tuesday" and print
Console.log (Str.substr (3,3));//Intercept "Tuesday" and print
However, if only know to intercept the character "Tuesday" in Str, but it is difficult to count the "Tuesday" exactly where in Str, you can also use indexof () to obtain the location, as follows:
var str= "Today is Tuesday";
var i=str.indexof ("star");//Gets the position of the character keyword, the first parameter of the IndexOf () method is the keyword to be searched, the second argument is the starting position of the search, and if the second argument is omitted, the default starting position is subscript 0.
Console.log (Str.slice (i,i+4));//Intercept "Tuesday" and print
Console.log (Str.substr (i,4));//Intercept "Tuesday" and print
Of course, it is required to intercept a string of some length from a certain starting position of a string, and it can be encapsulated into a function. So you can call it again and again.
function sub (str,startindex,len) {
return str.substr (Startindex,len);
}
Console.log (Sub ("ABCD",));
Front-End Learning Note IX-native JavaScript implements string interception