传统字符串的问题:
多行字符串问题: 多行字符串拼接要使用\或者每行+,要换行要使用\n
字符串使用变量: 要使用+
let age = 10;
let msg0 = 'Change the world \n\
by program.'
console.log(msg0);
let msg1 = 'Change the world \n' +
'by program.' + age
console.log(msg1);
模板字符串:
反引号: 在里面可以添加字符和任意换行
替换位的使用${}: 可以添加变量或变量表达式
let msg2 = `Change
the
world
by
program.${age}`
console.log(msg2);
字符串拓展方法:
String.prototype.includes
类似js: indexOf 但需要判断
let msg = 'hello';
console.log( msg.indexOf('h') ) // 返回0 代表索引
console.log( msg.indexOf('a') ) // 返回-1 表示不存在
console.log( msg.includes('h', 0) ) // 返回true 表示存在 0表示从哪个位置查找字符串
使用es5写includes兼容性写法
if(!String.prototype.includes){
String.prototype.includes = function(search, start){
if(typeof start !== 'number'){
start = 0;
}
if(start + search.length > this.length){
return false;
}else{
return this.indexOf(search, start) !== -1;
}
}
}
String.prototype.startsWith
let msg = 'hello';
console.log(msg.startsWith('e')); // 返回false 不是e开头
console.log(msg.startsWith('e', 1)); // 返回true 第二个字符是e开头
String.prototype.endsWith
let msg = 'hello';
console.log(msg.endsWith('lo')); // 返回true 是lo结尾
console.log(msg.endsWith('l', 1)); // 返回false 1表示第一位之前是l结尾 不包含第一位
String.prototype.repeat
let msg = 'hello';
console.log(msg.repeat(3)) // 返回hellohellohello 表示重复几次
154

被折叠的 条评论
为什么被折叠?



