Use substring() or slice() method (NN4, IE4), their specific usage is explained below.
The prototype of substring() is:
string.substring(from, to)
The first parameter from specifies the starting position of the substring in the original string (based on 0 index); the second parameter to is optional, and it specifies the ending position of the substring in the original string (based on 0). index), in general, it should be larger than from. If it is omitted, the substring will go to the end of the original string.
What happens if the parameter from accidentally becomes larger than the parameter to? JavaScript will automatically adjust the starting and ending positions of the substring, that is, substring() always starts from the smaller of the two parameters and ends with the larger one. Note, however, that it includes the character at the starting position, but not the character at the ending position.
var fullString = "Every dog has his day."; var section = fullString.substring(0, 4); // section is "Ever". section = fullString.substring(4, 0); // section is also "Ever". section = fullString.substring(1, 1); // section is an empty string. section = fullString.substring(-2, 4); // section is "Ever", same as fullString.substring(0, 4); slice()的原型为: string.slice(start, end)
The parameter start represents the starting position of the substring. If it is a negative number, it can be understood as the starting position from the last to last. For example, -3 means starting from the third from the last. The parameter end represents the ending position. Like start, it can also be a negative number. , its meaning also indicates the end of the penultimate number. The parameters of slice() can be negative, so it is more flexible than substring(), but less tolerant. If start is larger than end, it will return an empty string (example omitted).
There is another method is substr(), its prototype is:
string.substr(start, length)
From the prototype, we can see the meaning of its parameters. start represents the starting position, and length represents the length of the substring. The JavaScript standard discourages the use of this method.