字符串

字符串函数ES6

  1. startWith(str, index)
    返回boolean
    判断字符串是否从指定位置开始
    index可以省略表示 字符串是否从头开始

    const myName = "zheshi shenme?"
    myName.startsWith("zhe") //true
    myName.startsWith("shi", 3) //true
  2. endWith(str, index)
    返回boolean
    判断字符串是否结束在指定位置

    const myName = "zheshi shenme?"
    myName.endsWith("?") //true
    myName.endsWith("shi", 6) //true
  3. includes(str, index)
    返回boolean
    判断字符串从index往后的字符串中是否包含子字符串

    const myName = "zheshi shenme?"
    myName.endsWith("?") //true
    myName.endsWith("shi", 6) //true
  4. repeat(count)
    str.repeat(count)返回一个str重复coun次的字符串

    const str = "哈"
    let result = str.repeat(5) //哈哈哈哈哈
    

    可以使用repeat来实现对齐功能

模板字符串/字符

ES6中引入模板字符串

使用反引号括起来字符串 用${}括起来变量或表达式

const myName = "lyy"
const logStr1 = "my name is " + myName
const logStr = `my name is ${myName}`
console.log(logStr1)

特点:模板字符串会保留字符串中所有的空白符号 比如:空格、回车等

示例程序:
使用拼接html的字符串,可以直观的使用标签以及格式来书写html

特点:模板字符串是可以嵌套的

const todoArr = [
    {name: "go to home", completed: true},
    {name: "open book", completed: true},
    {name: "write book", completed: false}
]

const template = `
    <ul>
     ${todoArr.map(todo => `
        <li> 
        ${todo.name} completed: ${todo.completed ? `yes` : `no`} 
        </li>`).join("")} 
    </ul>
`
document.write(template)

标签模板字符串

标签模板字符串
用模板字符串作为函数的参数

 <script>
        function highlight(string, ...args) {
            //string 为 ["", " will to do ", ""]
            //args 为 变量数组  ["Mary", "go to home"]
            const highlighted = args.map(value => `<span class = "highlight"> ${value} </span>`)
            const str = string.reduce((preValue, currentValue, i) => `${preValue}${currentValue}${highlighted[i] || ""}`, "")
            return str
        }

        const userName = "Mary"

        const userTodo = "go to home"
        //``模板字符串作为函数参数 第一个参数为字符串被变量分割的字符串数组 
        // 当以变量靠头或者结尾时 前后会有空字符串
        // 第二个参数为所有的变量数组
        const template = highlight`${userName} will to do ${userTodo}`

        console.log(template)
        document.body.innerHTML = template
    
    </script>

用标签模板字符串预防xss攻击

xss攻击是指跨站脚本攻击,恶意将html或者js等web代码植入用户页面中进行攻击

可以使用DOMPurify.sanitize第三方框架来净化用户输入代码