-
在js中字符串可以看做一个特殊的数组, 所以大部分数组的属性/方法字符串都可以使用
-
1. 获取字符串长度 .length
let str = "abcd"; console.log(str.length); // 4 -
2. 获取某个字符 [索引] / charAt
let str = "abcd"; let ch = str[1]; // 高级浏览器才支持, 有兼容性问题, 不推荐使用 console.log(ch); // b let ch = str.charAt(1); // 没有兼容性问题 console.log(ch); // b -
3. 字符串查找 indexOf / lastIndexOf / includes
let str = "vavcd"; let index = str.indexOf("v"); // 0 let index = str.lastIndexOf("v"); // 2 console.log(index); let result = str.includes("c"); // true let result = str.includes("p"); // false console.log(result); -
4. 拼接字符串 concat / +
let str1 = "www"; let str2 = "it666"; let str = str1 + str2; // 推荐 console.log(str); // wwwit666 let str = str1.concat(str2); console.log(str); // wwwit666 -
5. 截取子串
let str = "abcdef"; let subStr = str.slice(1, 3); // bc let subStr = str.substring(1, 3); // bc 推荐 let subStr = str.substr(1, 3); // bcd 从索引为1的位置开始截取3个 console.log(subStr); -
6.字符串切割
// 数组转为字符串 let arr = [1, 3, 5]; let str = arr.join("-"); console.log(str); // 1-3-5 // 字符串转为数组 let str = "1-3-5"; let arr = str.split("-"); console.log(arr); // 135 -
7. 判断是否以指定字符串开头( startsWith) ES6
let str = "www.it666.com"; let result = str.startsWith("www"); console.log(result); // true -
8. 判断是否以指定字符串结尾 (endsWith) ES6
let str = "lnj.png"; let result = str.endsWith("png"); console.log(result); // true -
9. 字符串模板 ( `` ) ES6
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); // 我的名字是lnj, 我的年龄是34
89-字符串常用方法
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 一、concat() concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组,仅会返回被连接数组的...
