The String object es6 has expanded many methods, but many of them are related to character encoding. I have chosen several methods that I feel are more commonly used;
include the magic tool for searching characters
Remember how we used to determine whether a string object contains special characters?
var str='google';if(str.indexOf('o')>-1){console.log('yes');}else{console.log('no');}indexOf was originally just a method to get the corresponding position of the character, because if you cannot find it, the value -1 will be returned, which becomes a method to determine whether it is included. include is to determine whether it is included and directly return the 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 obtaining the location, and include is responsible for judging the inclusion relationship;
startsWith, endsWith easily determines the beginning and ends
startsWith is used to determine whether it is located at the head and endsWith is located at the tail. It can be said that these two methods are extensions of the include method;
let str='google';console.log(str.startsWith('g')); //trueconsole.log(str.endsWith('e')); //truerepeat Lazy welfare
As the name suggests, this method is to get the method after the string is repeated N times;
let str='google';console.log(str.repeat(3)); //googlegoogle
The repeat method accepts a numeric parameter, which can be formal or decimal. If it is a floating point type, the Math.floor method will be automatically called to convert it to an integer type;
let str='google';console.log(str.repeat(3.5)); //googlegoogleconsole.log(str.repeat(Math.floor(3.5))); //googlegoogle
The parameter can be 0 so that an empty string will be returned, but it cannot be a negative number, otherwise an error will be reported;
let str='google';console.log(str.repeat(0)); //''console.log(str.repeat(-3.5)); //RangeError: Invalid count value
padStart, padEnd
These two methods are actually extended under the ES7 standard, and their function is to automatically complete;
let str='goo';<br> str.padStart(5, 'le') // 'legoo'str.padStart(4, 'le') // 'lgoo'str.padEnd(5, 'le') // 'goole'str.padEnd(4, 'le') // 'gool'
These two methods are similar to accept two parameters. The first is the complete length and the second is the content to be supplemented. Since it is the es7 standard method, the browser cannot run directly now, so you can try to run it with the help of babel;
The above is the ES6 string extension method in JavaScript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!