29.字符串常用方法及字符串模板 发表于 2019-05-08 | 分类于 Javascript 在js中字符串可以看做一个特殊的数组,所以大部分数组的属性/方法字符串都可以使用 123456789101112131415161718192021222324252627282930311.获取字符串长度 .lengthlet str = "abcd";console.log(str.length);2.获取某个字符 [索引] / charAtlet str = "abcd";let ch = str[1];let ch = str.charAt(1);console.log(ch);3.字符串查找 indexOf / lastIndexOf / includeslet str = "vavcd";let index = str.indexOf("v");let index = str.lastIndexOf("v");console.log(index);let result = str.includes("p");//falseconsole.log(result);4.拼接字符串 concat / +let str1 = "www";let str2 = "it666";let str = str1 + str2; // 推荐let str = str1.concat(str2);console.log(str);5.截取子串 slice / substring / substrlet str = "abcdef";// let subStr = str.slice(1, 3);// let subStr = str.substring(1, 3);let subStr = str.substr(1, 3);console.log(subStr); stringObject.substr(start,length),length从start的index开始截取几个元素 12345678910111213141516171819202122232425262728293031323334353637383940414243441.字符串切割let arr = [1, 3, 5];let str = arr.join("-");//数组转为字符串,1-3-5 console.log(str); let str = "1-3-5"; let arr = str.split("-");//[ '1', '3', '5' ] console.log(arr);2.判断是否以指定字符串开头 ES6let str = "http://www.it666.com";let result = str.startsWith("www");console.log(result);3.判断是否以指定字符串结尾 ES6let str = "lnj.jpg";let result = str.endsWith("png");console.log(result);4.字符串模板 ES6let str = "";let str = '';let str = `www.it666.com`;console.log(str);console.log(typeof str);let str = "<ul>\n" + " <li>我是第1个li</li>\n" + " <li>我是第2个li</li>\n" + " <li>我是第3个li</li>\n" + "</ul>";let str = `<ul> <li>我是第1个li</li> <li>我是第2个li</li> <li>我是第3个li</li> </ul>`; let name = "lnj";let age = 34;// let str = "我的名字是" + name + ",我的年龄是" + age;let str = `我的名字是${name},我的年龄是${age}`;console.log(str);