String for of
ES6 added traversal interface is a string, the string may be such that the loop iterates for ... of.
const str='abcd';
for(let s of str){
console.log(s)
}
✨ template string
//es5
var name='小明',
age=18;
console.log('我叫'+name+'今年'+age+'岁')
//es6
console.log(`我叫${name}今年${age}岁`);
Note: Use template string
``
, that is not double quotes""
, not single quotes''
> ``
Usually in the upper left corner of the keyboard ESC
underneath the keys
New string method
String.includes(searchStr)
- Description: determining whether a string containing the target searchStr
{ const str='hello world'; console.log(str.includes('hello'));//true }
String.startsWith(searchStr,position?)
- Description: determining whether the string starts with searchStr, second argument position (optional) The default is 0, the first few characters showing the start determination rearwardly
{ const str='hello world'; console.log(str.startsWith('hello'));//true console.log(str.startsWith('abc'));//false console.log(str,startsWith('hello',1));//false console.log(str,startsWith('world',6));//true }
String.endsWith(searchStr,position?)
- Description: determining whether the string ends with searchStr, the second parameter the same position (optional) The default is the original length of the string, represents the first few characters is determined forwardly from start
{ const str='hello world'; console.log('endsWith', str.endsWith('world'));//true console.log('endsWith', str.endsWith('abc'));//false console.log('endsWith', str.endsWith('world',11));//true console.log('endsWith', str.endsWith('hello', 5));//true console.log('endsWith', str.endsWith('hello', 7));//false }
String.repeat(n)
- Description: repeat new method returns a string that represents the original string is repeated n times.
let str='abcd'; str=str.repeat(3); console.log(str);//abcdabcdabcd
ES2017 introduced complementary function of the whole length of the string. If a specified length is not enough, it will complement the head or tail.
1.String.padStart (length, fillStr?) Head completions
2.String.padEnd (length, fillStr?) Tail completion
- length: length of the string after the completion
- fillstr: filling a string, the default is a space
let str='5678'
console.log(str.padStart(8,'abc'));//abca5678
console.log(str.padEnd(8,'abc'));//5678abca
Examples
//提示日期
let str = '08-12'
console.log(str.padStart(10, 'yyyy-MM-dd'));//yyyy-08-12
Examples of the new string ES2019 TrimStart () and the TrimEnd () these two methods. Their behavior and trim () the same, trimStart () to eliminate blank string head, trimEnd () to eliminate trailing spaces. They are the new string is returned, does not modify the original string.
const s = ' abcd ';
s.trim() //"abcd"
s.trimStart() //"abc "
s.trimEnd() //" abc"