7 JavaScript 字符串方法
1 length()
length() 长度属性
var str = 'hello world';
console.log(str.length) //11字符,空格也是一个字符
2 charAt()
charAt() 获取指定的字符
var str = 'hello world';
console.log(str.charAt(1)); //e
3 charCodeAt()
charCodeAt() 获取指定的字符对应的字符编码
var str = 'hello world';
console.log(str.charCodeAt(1)); // 101
4 concat()
concat() 字符串拼接(一般不使用concat进行拼接,多使用“+”进行)
var str = 'hello world';
console.log(str.concat(' lxx')); //hello world lxx
5 slice()
slice(start,end) 切片分割字符串,从多少索引开始和结束;顾头不顾尾
var str = 'hello world';
console.log(str.slice(2)); //llo world
console.log(str.slice(2,4)); //ll
console.log(str.slice(-3,-1)); //rl相当于(8,10)
6 substring()
substring(start,end) 切片,从多少索引开始和结束;顾头不顾尾
var str = 'hello world';
console.log(str.substring(2)); //llo world
console.log(str.substring(2,4)); //ll
7 substr()
substr(start,end) 切片,从多少索引开始和结束;顾头顾尾
var str = 'hello world';
console.log(str.substr(2)); //llo world
console.log(str.substr(2,6)); //llo wo
8 indexOf()
indexOf() 从前往后数查看索引
var str = 'hello world';
console.log(str.indexOf('o')); //4
console.log(str.indexOf('o',6)); //7 从第6个索引往后查找
console.log(str[1]); //'e'
应用:
//查找e在str中的所有的位置
var str = ' He unfolded the map and set it on the floor.';
var arr = [];
var pos = str.indexOf('e');
console.log(pos);
while (pos>-1){
//找到当前e字符对应的位置
arr.push(pos);
pos = str.indexOf('e',pos+1);
}
console.log(arr);
9 lastIndexOf()
lastIndexOf() 从后往前数查看索引
var str = 'hello world';
console.log(str.lastIndexOf('o')); //7
console.log(str.lastIndexOf('o',6)); //4 从第6个索引往前查找
10 toUpperCase()
toUpperCase() 将字符转为大写
var str = 'Hello Lxx';
console.log(str.toUpperCase());
11 toLowerCase()
toLowerCase() 将字符转为小写
var str = 'Hello Lxx';
console.log(str.toLowerCase());
12 replace()
replace(a,b) 将字符串a替换成字符串b
var a = '1234567755';
var newStr = a.replace("4567","****");
console.log(newStr); //123****755
13 split()
split('a',1) 以字符串a分割字符串,并返回新的数组。如果第二个参数没写,表示返回整个数组,如果定义了个数,则返回数组的最大长度
var str = '我的天呢,a是嘛,你在说什么呢?a哈哈哈';
console.log(str.split('a'));//["我的天呢,", "是嘛,你在说什么呢?", "哈哈哈"]
14 trim()
trim() 格式化字符两端空格
var str = " woshi dsb ";
var ret = str.trim();
console.log(str.length); //13
console.log(ret.length); //9
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本