在底层,字符串是以字符数组的形式保存的。
因此,length属性可以用来获取字符串的一个长度。
var str = "hellowordl";
console.log(str.length); // 10
charAt()方法,可以返回字符串中指定位置的字符
也就是根据索引获取指定字符。
var str = "hellowordl";
// 效果和str[0]是一样的,没什么区别
console.log(str.charAt(0)); // h
console.log(str.charAt(5)); // w
charCodeAt()方法,可以获取指定位置字符的Unicode编码
var str = "hellowordl";
// h的字符编码就是104
console.log(str.charCodeAt(0)); // 104
String.formCharCode()方法,可以根据Unicode编码获取字符
正好和charCodeAt()相反,该方法需要用String调用。
console.log(String.fromCharCode(104)); // h
concat()方法,可以用来连接两个或多个字符串
作用和 + 一样。
var str = "hellowordl";
var res = str.concat("你好世界");
console.log(res); // hellowordl你好世界
indexof()方法,可以检索一个字符串中是否含有指定内容
如果字符串中含有该内容,则会返回其第一次出现的索引。
如果没有找到该内容,则返回-1。
var str = "hellowordl";
var res = str.indexOf("h");
var res2 = str.indexOf("l");
console.log(res); // 0,表示有且索引是0
console.log(res2); // 2,表示有且索引是2
// indexof()也可以指定第2个参数,指定开始查找的位置
var str = "hellowordl";
var res = str.indexOf("l",4); // 从索引为4的位置开始找
console.log(res); // 9
lastIndexof()方法,该方法用法和indexof()一样,不同的是indexof()是从前往后找,而lastIndexof()是从后往前找。
lastIndexof()也可以指定地2个参数,指定开始查找的位置。
var str = "hellowordl";
var res = str.lastIndexOf("o");
console.log(res); // 6
slice()方法,可以从字符串中截取指定的内容
该方法不会影响原字符串,会将内容返回。
参数: -第1个表示开始位置索引(包括开始位置)
-第2个表示结束位置索引(不包括结束位置)
如果省略第2个参数,则会截取到后面所有的。
也可以传递一个负数作为参数,负数的话将会从后边计算。
var str = "hellowordl";
var res = str.slice(0,2);
console.log(res); // he
substring()方法,可以用来截取一个字符串,和slice()相似
参数: -第1个表示开始位置索引(包括开始位置)
-第2个表示结束位置索引(不包括结束位置)
和slice不同的是,substring不能接收负值作为参数,如果传递了负数,则默认使用0。
且会自动调整参数位置,如果第2个参数小于第1个,则自动交换位置。
var str = "hellowordl";
var res = str.substring(1,3);
// 如果第2个参数小于第1个,则自动交换参数的位置
var res2 = str.substring(1,-1); // 相当于str.substring(0,1)
console.log(res); // h
split()方法,可以将一个字符串拆分为一个数组
参数:需要一个字符串作为参数,将会根据这个字符串去拆分数组。
如果传递一个空串,则会将每个字符都拆分为数组中的一个元素。
var str = "hellowordl";
var res = str.split("o"); // 根据字符串中国的0拆分
console.log(res); // ["hell", "w", "rdl"]
console.log(res[0]); // hell