此篇文章献给刚入们的小白,还有基础比较薄弱的朋友;
知识点都是比较简单,工作当中经常会用到;
如果觉得能用上就收藏,方便以后使用;
let s = "hello,world";
let ss = "你相信命运吗?";
let aa = s.split(',');
let bb = ss.split('');
console.log(aa);//["hello", "world"]
console.log(bb);//["你", "相", "信", "命", "运", "吗", "?"]
let s = "hello,world";
let ss = "你相信命运吗?";
let aa = s.charAt(6);
let bb = ss.charAt(3);
console.log(aa);//w
console.log(bb);//命
let s = "hello,world";
let ss = "你相信命运吗?";
let aa = s.charAt(s.length - 1);
let bb = ss.charAt(ss.length - 1);
console.log(aa);//d
console.log(bb);//#
两个值:第一个是开始位置,第二个是结束位置;
let s = "hello,world";
let ss = "你相信命运吗?";
let aa = s.substring(1,4);
let bb = ss.substring(2,5);
console.log(aa);//ell
console.log(bb);//信命运
一个值:字符串开始截取的位置;
let s = "hello,world";
let ss = "你相信命运吗?";
let aa = s.substring(1);
let bb = ss.substring(2);
console.log(aa);//ello,world
console.log(bb);//信命运吗?
let s = "hello,world";
let ss = "你相信命运吗?";
let aa = s.slice(1,4);
let bb = ss.slice(2);
console.log(aa);//ell
console.log(bb);//信命运吗?
let s = "hello,world,hello,world";
let ss = "你相信命运吗?你相信命运吗?";
let aa = s.indexOf('w');
let bb = ss.indexOf('相');
console.log(aa);//6
console.log(bb);//1
let s = "hello,world,hello,world";
let ss = "你相信命运吗?你相信命运吗?";
let aa = s.lastIndexOf('w');
let bb = ss.lastIndexOf('相');
console.log(aa);//18
console.log(bb);//8
let s = "hello,world,hello,world";
let ss = "你相信命运吗?你相信命运吗?";
let aa = s.indexOf('w',10);
let bb = ss.indexOf('相',3);
console.log(aa);//18
console.log(bb);//8
let s = "hello,world";
let ss = "你相信命运吗?";
let aa = s.replace('h','H');
let bb = ss.replace('你','他');
console.log(aa);//Hello,world
console.log(bb);//他相信命运吗?
let s = "hello,world";
let aa = s.toUpperCase();
console.log(aa);//HELLO,WORLD
记住,在JavaScript中字符串是固定不变的,类似replace()和toUpperCase()的方法都返回新字符串,原字符串本身并没有发生改变。
在ECMAScript 5中,字符串可以当做只读数组,除了使用charAt()方法,也可以使用方括号来访问字符串中的单个字符(16位值):
s = “hello, world”;
s[0] // => “h”
s[s.length – 1] // => “d”