ES6 This string object has expanded a lot of methods, but many are related to the character encoding, the individual selected a few feel more commonly used methods;
Includes search for character artifacts
Remember how we previously judged whether a string object contained a specially-designed character?
var str= ' Google ';
if (Str.indexof (' o ') >-1) {
console.log (' yes ');
} else{
console.log (' no ');
}
IndexOf would have been just a way to get the corresponding position of the characters, because finding a value that is not going to return 1 is a way to judge if it is included, and includes is to judge whether it contains a direct return boolean value;
Let str= ' Google ';
if (str.includes (' O ')) {
console.log (' yes ');
} else{
console.log (' no ');
}
This is more in line with semantics, IndexOf is responsible for acquiring position, includes is responsible for judging the inclusion relationship;
StartsWith, EndsWith easy to set the tail
StartsWith is used to judge whether it is in the head, EndsWith judge whether it is in the tail, it can be said that these two methods are the extension of includes method;
Let str= ' Google ';
Console.log (Str.startswith (' G ')); True
Repeat the Lazy man welfare
As the name suggests, this method is to get the string repeated n times after the method;
Let str= ' Google ';
Console.log (Str.repeat (3)); Googlegooglegoogle
The Repeat method accepts an argument of a numeric type, which can be either formal or decimal, and if it is a floating-point type, it automatically invokes the Math.floor method to the integer type;
Let str= ' Google ';
Console.log (Str.repeat (3.5)); Googlegooglegoogle
Console.log (Str.repeat (Math.floor (3.5));//googlegooglegoogle
The parameter can be 0 so that it returns an empty string, but not a negative number, otherwise it will be an error;
Let str= ' Google ';
Console.log (str.repeat (0)); '
Console.log (Str.repeat ( -3.5));//rangeerror:invalid count value
Padstart,padend, what do you need?
These two methods are in fact the extension of the ES7 standard method, the role is automatic completion;
Let str= ' goo ';<br> str.padstart (5, ' Le ')//' Legoo '
str.padstart (4, ' Le ')//' Lgoo '
str.padend (5, ' Le ')/ /' Goole '
str.padend (4, ' Le ')//' Gool '
The two methods are similar to accept two parameters, the first is the length of the complement, the second is to supplement the content, because it is ES7 standard method, now the browser can not run directly, you may try to use Babel operation;
The above is a small set of JavaScript to introduce the ES6 string extension method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!