在底层字符串是以字符数组的形式保存的 [“H” ,“e”,“l” ]
创建一个字符串
var str = “Hello Atguigu”;
在底层字符串是以字符数组的形式保存的[“H”,“e”,“l”]
//console.log(str. length);
console.log(str[1]);
length属性
-可以用来获取字符串的长度
charAt()
-可以返回字符串中指定位置的字符
-根据索引获取指定的字符
str = "Hello Atguigu";
var result = str.charAt(6);
console.log(result);
charCodeAt()
-获取指定位置字符的字符编码 (Uni code编码)
result = str. charCodeAt(0);
console.log(result);
String. formCharCode( )
-可以根据字符编码去获取字符
result = String. fromCharCode(20013) ;
console.log(result);
result = String. fromCharCode(0x2692);
console.log(result);
concat( )
-可以用来连接两个或多个字符串
-作用和+一样,且不会对原造成影响
result = str. concat("你好","再见");
console.log(result);
indexof( )
-该方法可以检索一 个字符串中 是否含有指定内容
-如果字符串中含有该内容,则会返回其第一次出现的索引
-如果没有找到指定的内容,则返回-1
-可以指定一个第二个参数, 指定开始查找的位置
str = "hello hatguigu";
result = str. index0f("h",l);
console.log(result);
lastIndex0f();
-该方法的用法和indexOf()一样,
-不向的是Indexof是从前往后找,而lastIndexOf是从后往前找,也可以指定开始查找的位置
slice()
-可以从字符串中截取指定的内容
-不会影响原字符串,而是将截取到内容返回
-参数:
第一个,开始位置的索引(包括开始位置)
第二个,结束位置的索引(不包括结束位置)
-如果省略第二个参数,则会截取到后边所有的
也可以传递一个负数作为参数,负数的话将会从后边计算
str = "abcdefghijk";
result = str.slice(1,2);
console. log(result);//b
console. log(str.slice(1,));//bcdefghijk
console. log(str.slice(1,-2));//bcdefghi
console. log(str.slice(1,-1));//bcdefghij
console. log(str.slice(1,0));//空,不能交换位置
console. log(str.slice());//abcdefghijk
substring()
-可以用来截取一个字符串,可以slice( )类似
-参数:
第一个:开始截取位置的索引(包括开始位置)
第二个:结束位置的索引(不包括结束位置)
-不同的是这个方法不能接受负值作为参数,
如果传递了一个负值,则默认使用0
-而且他还自动调整参数的位置,如果第二个参数小于第一个,则自动交换
str = "abcdefghijk";
console.log(str.substring(1,-3));//a,-3当0,再交换位置
console. log(str.substring(0,1));//a
console. log(str.substring(5,1));//bcde,交换位置
substr( )
-用来截取字符串
-参数:
1.截取开始位置的索引
2.截取的长度
str = "abcdefg";
result = str.substr(3,2);
console. log(result);//de
split()
-可以将一个字符串拆分为一个数组
-参数:
-需要一个字符串作为参数,将会根据该字符串去拆分数组
如果传递一个空串作为参数,则会将每个字符都拆分为数组中的一个元素
str = "abc,bcd,efg,hij";
result = str.split("d");
console.log(Array. isArray(result));//true
console.log(result);//["abc,bc", ",efg,hij"]
console.log(result[0]);//abc,bc
result1 = str.split("");
console.log(result1);//["a", "b", "c", ",", "b", "c", "d", ",", "e", "f", "g", ",", "h", "i", "j"]
toUpperCase( )
-将一个字符串转换为大写并返回
str = "abcdefg";
result = str. toUpperCase();
toLowerCase( )
-将一个字符串转换为小写并返回
str = "ABCDEFG";
result = str. toLowerCase( );