1. 程式人生 > 其它 >ES6中的字串

ES6中的字串

字串在程式語言中,一直是使用率很高的資料,雖說函式在js語言中是一等公民,但是字串,怎麼也能算得上是千年老二,下面我就一起和大家探討一下在es6中的一些新用法和特性,特別是在字串拼接的時候,會解放作為程式設計師的眼睛和雙手。大家也可以關注我的微信公眾號,蝸牛全棧。

一、模板字串:用`替換傳統的單引號或雙引號
1、傳統字串拼接

const str = "asasasas\n"
        +"sasasasasa\n"
        +"rrgtrgtegergre"
console.log(str) // 這個時候輸出的是換行的字串

2、es6中字串拼接

const str = `asasasas
        sasasasasa
        rrgtrgtegergre
        `
console.log(str) 
// 輸出的和上一段完全相同效果的字串

3、傳統字串中的運算並拼接

const a = 20
const b = 14
const c = "es"
const str = "我的年齡是:"+(a+b)+",我在講"+c
console.log(str) // 我的年齡是34,我在將es

4、es6字串中的運算並拼接:在使用`的基礎上,通過$和{}包裹變數。PS:這個語法在小編重構專案的時候,不知道省了多少眼藥水,真是大大的福利呀。

const a = 20
const b = 14
const c = "es"
const str5 = `我的年齡是${a+b},我在講${c}`
console.log() 
// 我的年齡是34,我在將es

二、巢狀模板:主要針對標籤中的動態class。小編之前在Vue專案中看到大量類似的例項,當時還不明白,現在才知道是個啥。
1、傳統方式

const isLarge = () => {
    return true
}

let class1 = 'icon'
class1 += isLarge()?' icon-big':" icon-small"
console.log(class1) // 'icon icon-big'

2、es6新方式

const isLarge = () => {
    return true
}
const class1 
= `icon icon-${isLarge()?' icon-big':" icon-small"}` console.log(class1) // 'icon icon-big'

三、帶標籤的模板字串

const foo = (a,b,c,d) =>{
    console.log(a)
    console.log(b)
    console.log(c)
    console.log(d)
}

foo(1,2,3,4) // 1 2 3 4

const name = "lilei"
const age = 34
foo`這是${name},他的年齡是${age}歲` // ["這是",",他的年齡是","歲"]  lilei  34 undefind

四、includes:判斷指定字串是否在其他字串內,存在返回true,不存在返回false

// indexOf 判斷字串中是否含有某個字串,如果存在,返回該字串對應的下標,不存在返回-1
const str = "1234"
console.log(str.indexOf("2")) // 1
const str = "1234"
console.log(str.includes("2")) // true

五、startWith:判斷自定義字串是否以指定字串開始,返回布林值

const str = "1234"
console.log(str.startsWith("12")) // true

六、endWith:判斷自定字串是否以指定字串結束,返回布林值

const str = "1234"
console.log(str.endtWith("12")) // false

七、repeat:重複指定字串指定次數,返回新字串

const str = "1234"
const newStr = str.repeat(3)
console.log(newStr) // 123412341234