13.字符串
1. 字符串常用的几个方法:
(1)字符串中是否包含某个字符串(indexOf的替代方案):
let str1 = "abcdefgh"; let str2 = "def"; let res = str1.includes(str2); console.log(res); //true
(2)得到一个重复n次的字符串:
let str1 = "abc"; let res = str1.repeat(2); console.log(res); //abcabc
(3)字符串是否为某个字符串的开始(可用来判断url是否有http):
let str1 = "abcdefgh"; let str2 = "def"; let res = str1.startsWith(str2); console.log(res); //false
(4)字符串是否为某个字符串的结尾(可用来判断后缀名):
let str1 = "abcdefgh"; let str2 = "def"; let res = str1.endsWith(str2); console.log(res); //false
(5)用给定的字符串在尾部拼接到指定长度:第一个参数是长度,第二个参数是要拼接的值
let str1 = "abc"; let str2 = "def"; let res = str1.padEnd(10,str2); console.log(res); //abcdefdefd
(6)用给定的字符串在首部拼接到指定长度:第一个参数是长度,第二个参数是要拼接的值
let str1 = "abc"; let str2 = "def"; let res = str1.padStart(10,str2); console.log(res); //defdefdabc
2. 字符串转对象(注意:字符串必须是JSON格式,即键名必须用双引号包裹):
//JSON格式:str1={"id":1,"name":"张三","age":28} let res = JSON.parse(str1);
3. 判断字符串当中是否包含某个特定的子串
//1.includes() 判断字符串是否包含某个特定的子串 this.res.includes('png'); //2.startsWith() 判断字符串是否以特定的子串开始 this.res.startsWith('png'); //3.endsWith() 判断字符串是否以特定的子串结束 this.res.endsWith('png');
4. 字符串拼接
//1.字符串需要用一对反引号(~)包裹,它可以定义多行字符串,只用一对反引号。 //2.要拼进去的数据需要放在${}里面。 //3.大括号里面可以进行运算。 //4.大括号里面可以调用函数。 fn(){ return 'hello'; }, clickString(){ //方式一:直接拼接 let user1='<div><span>'+this.res+'</span><span>'+this.res+'</span></div>'; //方式二:带格式的拼接 let user2=`<div><span>${this.res}</span><span>${this.fn() +this.res}</span></div>` }
转载请注明原文链接:https://www.cnblogs.com/chenJieLing/