1 for...of 字符串的遍历接口
for(let i of "abc"){
console.log(i);
}
// a
// b
// c格式:str.includes(searchstring[, position])
与indexof的对比:
indexof:返回下标,判断是否包含某字符串,下标是字符串的位置
includes:返回布尔值,是否包含某字符串,如果只是判断字符串中包含,此法可行。
var s = "hello";
// es5
s.indexOf("o"); // 4
// es6
s.includes("o"); // true
s.includes("d"); // false
s.includes("h", 2); // false 从第三个字符开始找格式:str.startsWith(searchString[, position])
var s = "hello world";
// es5
s.indexOf("hello"); // 0 等于0表示就在源字符串头部
// es6
s.startsWith("hello"); // true
s.startsWith("world"); // false
s.startsWith("world", 6); // true格式:str.endsWith(searchString[, position])
var s = "hello world";
// es5
String.prototype.endWith=function(endStr){
var d=this.length-endStr.length;
return (d>=0&&this.lastIndexOf(endStr)==d)
}
s.endWith("world"); // true
// es6
s.endsWith("world"); // true
s.endsWith("world", 5); // false
s.endsWith("hello", 5); // truevar s = "s"; s.repeat(3); // sss s.repeat(2.6); // ss 小数会被取整 s.repeat(-2); // RangeError 报错 s.repeat(0); // ""
它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量,好处相当明显,不用再拼接字符串,使用模板字符串内部可以使用变量了。
// es5 输出模板通常是如下格式,相当繁琐还不方便
var name="Bob",time="today";
var resultStr = "hello "+name+", how are you "+time+'?'; //hello Bob, how are you today?
// es6 模板字符串
console.log(`string text line 1
string text line 2`);
//string text line 1
//string text line 2
// 直接用${变量名}表示
`Hello ${name}, how are you ${time}?` // Hello Bob, how are you today?
// 使用表达式
var obj={a:1,b:2};
`${obj.a+obj.b}` // 3
// 使用函数
function fn() {
return "Hello World";
}
`this is fn return str: ${fn()}` // this is fn return str: Hello World具体es6关于字符串的变化、拓展请查看MDN官网
【相关推荐】
1. 特别推荐:“php程序员工具箱”V0.1版本下载
2. 免费js在线视频教程
3. php.cn独孤九贱(3)-JavaScript视频教程
以上就是es6的基础介绍--字符串的拓展的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号