ES6——字符串

1. 子串的识别

  • includes():返回布尔值,判断是否找到参数字符串。
  • startsWith():返回布尔值,判断参数字符串是否在原字符串的头部。
  • endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部
let string = "apple,banana,orange";
string.includes("banana");     // true
string.startsWith("apple");    // true
string.endsWith("apple");      // false
string.startsWith("banana",6)  // true  可以设置一个起始位置

2. 字符串重复

  • repeat():返回新的字符串,表示将字符串重复指定次数返回
console.log("Hello,".repeat(2));  // "Hello,Hello,"

3. 字符串补全

  • padStart:返回新的字符串,表示用参数字符串从头部补全原字符串。
  • padEnd:返回新的字符串,表示用参数字符串从头部补全原字符串。
    以上两个方法接受两个参数,第一个参数是指定生成的字符串的最小长度,第二个参数是用来补全的字符串。如果没有指定第二个参数,默认用空格填充。
console.log("h".padStart(5,"o"));  // "ooooh"
console.log("h".padEnd(5,"o"));    // "hoooo"
console.log("h".padStart(5));      // "    h"
  • 如果指定的长度大于或者等于原字符串的长度,则返回原字符串:
console.log("hello".padStart(5,"A"));  // "hello"

*常用于补全位数:

console.log("123".padStart(10,"0"));  // "0000000123"

4. 模板字符串

  • 普通字符串
let string = `Hello'\n'world`;
console.log(string); 
// "Hello'
// 'world"
  • 多行字符串:
let string1 =  `Hey,
can you stop angry now?`;
console.log(string1);
// Hey,
// can you stop angry now?
  • 字符串插入变量和表达式。
let name="ben";
let age=20;
let info=`my name is ${name},i am ${age+3} years old`;
console.log(info)
  • 填写html
$('#list').html(`
  • first
  • second
`);

5. 标签模板



你可能感兴趣的:(ES6——字符串)