es6新語法系列,查找字符串,模板字符串


一、模板字符串:

ES6引入了一種新型的字符串字面量語法,我們稱之為模板字符串(template strings)。除了使用反撇號字符 ` 代替普通字符串的引號 ' 或 " 外,它們看起來與普通字符串並無二致。在最簡單的情況下,它們與普通字符串的表現一致:

拼接字符串時用``,例如:console.log(`用戶 ${user.name} 未被授權執行 ${action} 操作。`)

二、for...of字符串的遍歷接口

for(let i of "abc"){
    console.log(i);
}
// a
// b
// c
//空格也會被遍歷出來

三、includes判斷是否包含某字符串,返回布爾值

與indexOf的區別:indexOf返回字符串的下標,找不到則返回-1

        includes返回布爾值,只能判斷是否存在

var s = "hello";
// es5
s.indexOf("o"); // 4
// es6
s.includes("o"); // true
s.includes("d"); // false
s.includes("h", 2); // false 從第三個字符開始找

四、startsWith 參數字符串是否在源字符串的頭部,返回布爾值

格式:str.startsWith(searchString[, position])

var s = "hello world";
// es5
s.indexOf("hello"); // 0 等於0表示就在源字符串頭部
// es6
s.startsWith("hello"); // true
s.startsWith("world"); // false
s.startsWith("world", 6); // true

五、endsWith 跟startsWith相反,表示參數字符串是否在源字符串的尾部,返回布爾值

格式:str.endsWith(searchString[, position])

var s = "hello world";
// es5
String.prototype.endWith=function(endStr){
  var d=this.length-endStr.length;
  return (d>=0&&this.lastIndexOf(endStr)==d)
}
s.endWith("world"); // true
// es6
s.endsWith("world"); // true
s.endsWith("world", 5); // false
s.endsWith("hello", 5); // true

六、repeat 將原字符串重復n次,返回一個新字符串

var s = "s";
s.repeat(3); // sss
s.repeat(2.6); // ss 小數會被取整
s.repeat(-2); // RangeError 報錯
s.repeat(0); // ""

七、模板字符串 是增強版的字符串,用反引號(`)標識

它可以當作普通字符串使用,也可以用來定義多行字符串,或者在字符串中嵌入變量,好處相當明顯,不用再拼接字符串,使用模板字符串內部可以使用變量了。

// es5 輸出模板通常是如下格式,相當繁瑣還不方便
var name="Bob",time="today";
var resultStr = "hello "+name+", how are you "+time+'?'; //hello Bob, how are you today?
// es6 模板字符串
console.log(`string text line 1
string text line 2`);
//string text line 1
//string text line 2

// 直接用${變量名}表示
`Hello ${name}, how are you ${time}?` // Hello Bob, how are you today?
// 使用表達式
var obj={a:1,b:2};
`${obj.a+obj.b}` // 3
// 使用函數
function fn() {
  return "Hello World";
}
`this is fn return str: ${fn()}` // this is fn return str: Hello World

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM