字符串扩展

作者: 好奇男孩 | 来源:发表于2018-05-13 02:41 被阅读15次

    ES6 加强了对 Unicode 的支持,并且扩展了字符串对象

    字符的 Unicode 表示法

    //es5
    "\uD842\uDFB7"
    // "𠮷"
    "\u20BB7"
    // " 7"
    
    //es6
    "\u{20BB7}"
    // "𠮷"
    

    for...of循环遍历

    for (let code of 'foo') {
      console.log(code)
    }
    // "f"
    // "o"
    // "o"
    

    repeat()

    返回一个新字符串,表示将原字符串重复n次。

    'hello'.repeat(2) // "hellohello"
    

    padStart(),padEnd()

    padStart()用于头部补全,padEnd()用于尾部补全

    'x'.padStart(5, 'ab') // 'ababx'
    'x'.padStart(4, 'ab') // 'abax'
    
    'x'.padEnd(5, 'ab') // 'xabab'
    'x'.padEnd(4, 'ab') // 'xaba'
    
    

    字符串模板

    let website = 'xiaohui'
    let who = 'You'
    let str = `Hi
    This is ${website}.
    ${who} can study frontend here
    '
    console.log(str)
    

    多行字符串

    let str =`
    Hi,
    This is baidu.com.
    You can study frontend here.
    `
    console.log(str)
    
    

    标签模板

    是函数调用的一种特殊形式..紧跟在后面的模板字符串就是它的参数。

    alert`123`
    // 等同于
    alert(123)
    

    模板字符里面有变量,就不是简单的调用了,而是会将模板字符串先处理成多个参数,再调用函数

    let a = 5;
    let b = 10;
    
    tag`Hello ${ a + b } world ${ a * b }`;
    // 等同于
    tag(['Hello ', ' world ', ''], 15, 50);
    

    相关文章

      网友评论

        本文标题:字符串扩展

        本文链接:https://www.haomeiwen.com/subject/uxekdftx.html