字符串的遍历
空格也会被遍历
返回字符串给定位置的字符
es5提供了charAt方法
let str = 'hello world'
console.log(str.charAt(0)) //h
es6提供了at方法,目前还只是一个提案
let str = 'hello world'
console.log(str.at(0)) //h
字符串中是否包含某个字符
es5 提供了indexOf()方法可返回某个指定的字符串值在字符串中首次出现的位置
/* indexOf(searchValue,fromIndex);
* searchValue 要查找的字符
* fromIndex 从哪开始查找,默认是重头开始0,取值范围是0到str.length - 1
* return 首次出现的位置 或者 -1
*/
let str = 'hello world'
console.log(str.indexOf('h')) // 0
console.log(str.indexOf('world',3)) // 6
console.log(str.indexOf('d',str.length - 1)) //10
console.log(str.indexOf('k')) //-1
es6提供了includes()、startsWith()、endsWidth()
/*
* includes(searchValue,fromIndex) 返回布尔值,表示是否找到了searchValue
* startsWith(searchValue,fromIndex)返回布尔值,表示searchValue是否在str的头部
* endsWidth(searchValue,fromIndex)返回布尔值,表示searchValue是否在str的尾部
* searchValue要查找的字符
* fromIndex开始搜索的位置
* */
let str = 'hello world'
console.log(str.startsWith('hello')) //true
console.log(str.endsWith('hello')) //false
console.log(str.includes('hello')) //true
console.log(str.startsWith('world',6)) //true
console.log(str.endsWith('hello',5)) //true 从第5个到第0个
console.log(str.includes('hello',6)) //false
repeat(N)重复原字符串N次,返回一个新字符串
//N是整数
let str = 'x';
console.log(str.repeat(3)) // 'xxx'
console.log(str.repeat(0)) // ''
//N是小数,会向下取整
console.log(str.repeat(2.9)) // 'xx'
//N 是负数或Infinity,报错
console.log(str.repeat(-1))//Uncaught RangeError: Invalid count value at String.repeat (<anonymous>)
console.log(str.repeat(Infinity))//Uncaught RangeError: Invalid count value at String.repeat (<anonymous>)
/*N 是0的情况
* 0到-1之间的小数,则等同于0
* NaN 等同于0
* */
console.log(str.repeat(NaN)) // ''
console.log(str.repeat(-0.9)) // ''
padStart(minLength,str),padEnd(minLength,str)补全字符串
/*padStart(minLength,str),padEnd(minLength,str)
* minLength 指定字符串的最小长度
* str 用来补全的字符串
* */
let str = 'hu'
console.log(str.padStart(6,'ke')) //'kekehu' 在原字符串之前补充
console.log(str.padEnd(6,'ke')) //'hukeke' 在原字符串之后补充
//原字符串的长度> 或 =指定的最小长度,则返回原字符串
console.log(str.padStart(2,'ke')) // hu
console.log(str.padEnd(1,'ke')) // hu
//用来补全的字符串+原字符串 > 指定的最小长度,截取超出位数的补全字符串
console.log(str.padStart(6,'helloworld')) //hellhu
//省略第二个参数,用空格补充
console.log(str.padStart(6)) // ' hu'
//padStart()的常见用途是为数值补全指定位数
let s = '111'
console.log(s.padStart(10,'0'))// '0000000111'
模板字符串
//字符串中嵌入变量
let name = 'huke'
let str = `hello world,hello ${name}`
console.log(str) //'hello world,hello huke'
//多行字符串
let str1 = `<p>hello world
<span>!!!</span>
</p>`
console.log(str1)
在模板中嵌入变量,需要将变量名写在${ }中