字符串
字符串
const profile = {
name: "kangkang",
age: 21,
sayName: function () {
console.log("my name is " + this.name)
},
sayName2: function() {
console.log(`my name is ${this.name}`)
},
sayName3: function() {
console.log(`my name is ${this.name} ${`年龄是 ${this.age}`}`)
}
}
练习
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>模版字符串</title>
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid #eee;
}
th {
text-align: center;
}
</style>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript">
const tmpl = function() {
return {
title: "前端",
data: [{
title: '布局基础',
date: ["html", "css"]
}, {
title: '网页特效',
date: ["javascript", "jquery"]
}, {
title: '框架',
date: ["bootstrap", "vue"]
}]
}
}
let tmpl2= tmpl()
let {title: Btitle, data: datas} = tmpl2
let value =[]
value.push(Btitle)
datas.forEach((e,i) => {
let {title:tmp,date:[tmp2,tmp3]} = e
value.push(tmp)
value.push(tmp2)
value.push(tmp3)
})
let tNode = document.createElement("table")
tNode.innerHTML= `<th>${value[0]}</th>
<tr>
<td>${value[1]}</td>
<td>${value[2]}</td>
<td>${value[3]}</td>
</tr>
<tr>
<td>${value[4]}</td>
<td>${value[5]}</td>
<td>${value[6]}</td>
</tr>
<tr>
<td>${value[7]}</td>
<td>${value[8]}</td>
<td>${value[9]}</td>
</tr>
`
document.body.appendChild(tNode)
</script>
</body>
</html>
字符串新的方法
- padStart
let str = "haha" str.padStart(5,"gou") //"ghaha"
将gou
添加到str前面,当长度超过(第一个参数)拼接之和后会截取掉用来拼接的字符
-
padEnd
与padStart相同,不过是在末尾添加
-
repeat
let str = "ab".repeat(8) // abababababababab
-
startsWith
检测某个字符串是否在另外字符串的开头
let str = "my name is kangkang" str.startsWith("my ")// true
-
endsWith
检测某个字符串是否在另外字符串的开头
let str = "my name is kangkang" str.endsWith("kang")// true
-
includes
检测某个字符串是否在另外字符串内
let str = "my name is kangkang" str.includes(" is")// true
遍历字符串
思路:转换为字符数组来进行遍历
let str = "kangkang"
let str2 = Array.prototype.slice.call(str)//
let str3 = str.split("")
let str4 = [...str]
let [...str5] = str
str5.forEach((e) => {
console.log(e)
})
而遍历的作用就是为了操作
for-of
遍历字符串
let str = "abcdefg" for
Unicode
"🐶".codePointAt(0).toString(16) // "1f436"
"\u{1f436}" //"🐶"
(∩_∩)-----代码改变生活。