es6中对字符串操作时,会先将字符串转换成一个类似数组的一个对象,因为他是一个对象,所以通过他的length属性可以获得他的长度。
比如:
//将字符串转为类似数组的一个对象
let
[
x
,
y
,
z
]=
'123'
console
.
log
(
x
,
y
,
z
)
// 1 2 3
//既然说它是一个类似数组的一个对象,那么他的长度length属性可以这样获得
let
{
length
}=
'971211'
console
.
log
(
length
)
//6
字符串的方法:
//indexOf() es5中判断字符串中有没有指定字符,有返回该字符在字符串中出现的第一个索引
//includes() 判断字符串中有没有指定的字符,有的话返回true 没有返回false
//第二个参数:开始查找的索引,默认是0
let
str
=
'qwertyuiopasdfghjk'
let
is
=
str
.
includes
(
'2'
)
//false
let
it
=
str
.
includes
(
'k'
)
//true
// console.log(it)
//startsWith() 是不是以某个字符作为开头
//endsWith() 是不是以某个字符作为结尾
let
starts1
=
str
.
startsWith
(
'q'
)
//true
let
starts2
=
str
.
startsWith
(
'qwe'
)
//true
let
starts3
=
str
.
startsWith
(
'ewq'
)
//false
let
ends1
=
str
.
endsWith
(
'k'
)
//true
let
ends2
=
str
.
endsWith
(
'ghjk'
)
//true
let
ends3
=
str
.
endsWith
(
'kjhg'
)
//false
//repeat(n) 将字符串重复n次返回 原字符串不变
/*
1.n如果是小数,则向下取整
2.n如果是负数&infinity 则报错
3.n如果是0->-1 之间的数 先向下取整运算结果为0 输出为空字符串''
4.n如果是NaN => 0 输出为空字符串''
5.n如果是数字字符串 会先将字符串转换为数字,然后再去运算
*/
let
str2
=
str
.
repeat
(
3
)
// qwertyuiopasdfghjkqwertyuiopasdfghjkqwertyuiopasdfghjk
console
.
log
(
str2
)
//
模板字符串的使用:
比如向body中插入一段html代码
//以前的做法
let
str
=
'I LOVE YOU'
document
.
body
.
innerHTML
=
'<h1>'
+
str
+
'</h1>'
//es6 并且{}中可以运算
document
.
body
.
innerHTML
=
`<h1>
${
str
}
</h1>`
//模板字符串还有另一个功能 就是保留换行和空格
console
.
log
(
'hahhahah
\n
hahahahah'
);
/*
hahhahah
hahahahah
*/
let
str2
=
`hahhaha
gagagagag
hahahahah`
console
.
log
(
str2
)
/*
hahhaha
gagagagag
hahahahah
*/