数组和字符串是笔试题中出现频率最高的两种数据类型,在上一篇博文,我对JavaScript 数组的方法进行了总结,这篇博文我将对字符串的方法进行总结,由于字符串和数组的方法具有相似性,读者可以对比阅读。
String 类型提供了很多方法,用于辅助完成对字符串的解析和操作。操作字符串的方法主要有以下:
- charAt() 和 charCodeAt()
- indexOf() 和 lastIndexOf()
- concat()
- slice()
- substr()
- substring()
- trim()
- toLowerCase() 和 toUpperCase()
- match()
- search()
- replace()
- split()
- localeCompare()
- fromCharCode()
下面分别介绍各个方法的具体使用方法。
1、charAt() 和 charCodeAt()
charAt():接收一个参数:索引位置,返回指定索引位置的字符。需要注意的是:在JavaScript中没有char类型,所以返回的返回的是长度为1的字符串。
charCodeAt():与charAt()方法类似,不过返回的不是字符而是对应索引位置的字符编码。
var str = "hello world";
console.log(str.charAt(4)); // o
console.log(str.charCodeAt(4)); //111
console.log(str[4]); //o
上述代码通过charAt(4)找到索引为4处的字符“o”,通过charCodeAt(4)找到索引为4处字符“o”的字符编码“111”。 ES5 还定义了另一个访问个别字符的方法,可以使用方括号加数字索引来访问字符串中的特定字符。
2、indexOf() 和 lastIndexOf()
indexOf():在一个字符串中从字符串的开头向后搜索给定的子字符串,然后返子字符串的位置(如果没有找到该子字符串,则返回-1)。
lastIndexOf():作用与indexOf()一样,不同的是lastIndexOf()从字符串的末尾向前搜索子字符串。
这两个方法都可以接收两个参数:第一个是需要搜索的子字符串,第二个是从字符串中的哪个位置开始搜索(可选)。
var str = "hello world";
console.log(str.indexOf("l")); //2
console.log(str.lastIndexOf("l")); //9
console.log(str.indexOf("l",4)); //9
console.log(str.lastIndexOf("l",4)); //3
3、concat()
concat():用于将一或多个字符串拼接起来,返回拼接得到的新字符串。可以接收多个参数,表示需要拼接的字符串。
var str = "hello world";
var strConcat = str.concat("!"," Welcome to my blog!");
console.log(str); // hello world (原字符串不变)
console.log(strConcat); // hello world!