天天看點

ES6字元串的拓展方法

1、子串的識别

ES6 之前判斷字元串是否包含子串,用 indexOf 方法,ES6 新增了子串的識别方法。

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      

注意點:

這三個方法隻傳回布爾值,如果需要知道子串的位置,還是得用 indexOf 和 lastIndexOf 。這三個方法如果傳入了正規表達式而不是字元串,會抛出錯誤。而 indexOf 和 lastIndexOf 這兩個方法,它們會将正規表達式轉換為字元串并搜尋它。

2、字元串重複

repeat():傳回新的字元串,表示将字元串重複指定次數傳回。

console.log("Hello,".repeat(2));  // "Hello,Hello,"      

如果參數是小數,向下取整

console.log("Hello,".repeat(3.2));  // "Hello,Hello,Hello,"      

如果參數是 0 至 -1 之間的小數,會進行取整運算,0 至 -1 之間的小數取整得到 -0 ,等同于 repeat 零次

console.log("Hello,".repeat(-0.5));  // ""      

如果參數是 NaN,等同于 repeat 零次

console.log("Hello,".repeat(NaN));  // ""      

如果參數是負數或者 Infinity ,會報錯:

console.log("Hello,".repeat(-1));  
// RangeError: Invalid count value

console.log("Hello,".repeat(Infinity));  
// RangeError: Invalid count value      

如果傳入的參數是字元串,則會先将字元串轉化為數字

console.log("Hello,".repeat("hh")); // ""
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("hello".padEnd(10,",world!"));  // "hello,worl"      

常用于補全位數:

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

4、模闆字元串

模闆字元串相當于加強版的字元串,用反引号 `,除了作為普通字元串,還可以用來定義多行字元串,還可以在字元串中加入變量和表達式。

普通字元串:(使用\n換行)

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?      

字元串插入變量和表達式。

變量名寫在 {} 中可以放入 JavaScript 表達式。

let name = "Mike";
let age = 27;
let info = `My Name is ${name},I am ${age+1} years old next year.`
console.log(info);
// My Name is Mike,I am 28 years old next year.      

字元串中調用函數:

function f(){
  return "have fun!";
}
let string2= `Game start,${f()}`;
console.log(string2);  // Game start,have fun!      

注意要點:

模闆字元串中的換行和空格都是會被保留的

innerHtml = `<ul>
  <li>menu</li>
  <li>mine</li>
</ul>
`;
console.log(innerHtml);
// 輸出
<ul>
 <li>menu</li>
 <li>mine</li>
</ul>      

5、标簽模闆

标簽模闆,是一個函數的調用,其中調用的參數是模闆字元串。

alert`Hello world!`;
// 等價于
alert('Hello world!');      

當模闆字元串中帶有變量,會将模闆字元串參數處理成多個參數。

function f(stringArr,...values){
 let result = "";
 for(let i=0;i<stringArr.length;i++){
  result += stringArr[i];
  if(values[i]){
   result += values[i];
        }
    }
 return result;
}
let name = 'Mike';
let age = 27;
f`My Name is ${name},I am ${age+1} years old next year.`;
// "My Name is Mike,I am 28 years old next year."
 
f`My Name is ${name},I am ${age+1} years old next year.`;
// 等價于
f(['My Name is',',I am ',' years old next year.'],'Mike',28);      
function f(stringArr,...values){
 let result = "";
 for(let i=0;i<stringArr.length;i++){
  result += stringArr[i];
   if(values[i]){
     result += String(values[i]).replace(/&/g, "&")
               .replace(/</g, "<")
               .replace(/>/g, ">");
    }
 }
 return result;
}
name = '<Amy&MIke>';
f`<p>Hi, ${name}.I would like send you some message.</p>`;
// <p>Hi, <Amy&MIke>.I would like send you some message.</p>      
i18n`Hello ${name}, you are visitor number ${visitorNumber}.`;  
// 你好**,你是第**位通路者