ES6字符串棋凳,字符串模板
es6對字符串新添加了一些方法邪驮,最重要的引入了字符串模板(string template),下面來看看ES6字符串改動。
1.新增方法
1. startsWith(str[, pos]): 是否已什么字符開始刃唤,pos表示搜索起始位置,不寫默認為0
2. endsWith(str[, pos]): 是否已什么字符結束白群,pos同上
3. includes(str[, pos]): 是否包含某個字符
4. repeat(times): times表示重復多少次
eg:
let message = "hello world";
message.startsWith("he"); // true
message.startsWith("he", 4); // false
message.endsWith("rld"); // true
message.endsWith(" w", 7) // true
message.includes("or"); // true
message.includes("or", 8); // false
let s = "hello";
s.repeat(0); // ""(empty string)
s.repeat(2); // "hellohello"
// 一般可用于添加縮進
" ".repeat(4); // " "
2.模板字符串
模板字符串用backstick表示``(Esc下面那個鍵)尚胞,能夠實現多行,實現替代,標簽模板字符串
1.實現多行
eg:
// ES6之前實現方法
var message = "hello \n\
world"; // "\n"表示換行轉義帜慢, "\"表示字符串連續(xù)
// 或者
var message = "multiline\nstring";
// ES6模板字符串
var message = `hello
world`;
2.實現替代
eg:
function total(count, price) {
console.log(`${count} items cost $${(count * price).toFixed(2)}.`);
}
total(10, 0.25); // 10 items cost $2.50.
3.帶標簽的模板字符串(tagged template string)
表示字符串字面值(literals)和模板替代(substitutions)交替出現(interwoven),literals,substitutions均為數組笼裳,literals長度比substitutions大1
tag`${count} items cost $${(count * price).toFixed(2)}.`;
// tag為一個函數名唯卖,可以是任意名稱,下面會講到
// literals = ["", " items cost $", "."] 第一個為空字符串
// substitutions = ["${count}", "${(count * price).toFixed(2)}"]
tag函數為:
// 交替出現
// substitutions.length === literals.length - 1
function tag(literals, ...substitutions) {
let result = "";
for (let i = 0; i < substitutions.length; i++) {
result += literals[i];
result += substitutions[i];
}
result += literrals[literals.length - 1];
return result;
}
4.String.raw()標簽模板字符串方法
原生的方法躬柬,將轉義也表示出來拜轨,顯示原始字符串
var message1 = "hello\n world";
console.log(message1); \\ "hello
\\ world"
var message2 = "hello\n world";
String.raw(message2); \\ "hello\n world"
3.其他方面的改變
1.正則表達式
1- 新添加"u","y" flags
2- 新添加 flags 屬性,es5沒有
3- 復制可以更改flag
// es5獲取flags
function getFlags(re) {
var text = re.toString();
return text.substring(text.lastIndexOf("/") + 1, text.length);
}
var re = /\d/gi;
getFlags(re); // "gi"
// ES6
var re = /\d/gi;
re.source; // "\d"
re.flags; // "gi"
// ES5可以復制正則表達式,但是不能更改flags允青,ES6則可以
var re1 = /[a-z]/gi;
var re2 = new RegExp(re1, "m"); // 在ES5拋出錯誤橄碾,ES6正常
2.增加了對unicode的支持
主要差別在于超出BMP(BASE MULTILINGUAL PLAINS) 字符使用point方法將原來2個字符表示的字符,改為1個字符
// 添加方法
charPointAt(); // es5為charCodeAt()
String.fromPointCode(); // es5的為String.fromCharCode()
總結
- 新添加一些方法startsWith(), endsWith(), includes(), repeat()
- 添加模板字符串颠锉,及標簽模板字符串(實質是函數)
- 正則表達式方面的改動法牲,對unicode的支持及其相應的方法
2016/9/11 12:12:50