1、查找字符串中的字符串
indexOf()方法
返回的是字符串中指定文本首次出现的位置。
LastIndexOf()方法
返回字符串中指定文本最后一次出现的位置。
如果未找到文本,indexOf() 和 lastIndexOf() 都返回 -1:
这两种方法都接受第二个参数作为搜索的开始位置:
lastIndexOf() 方法向后搜索(从末尾到开头),意思是:如果第二个参数是 15,则从位置 15 开始搜索,一直搜索到字符串的开头
2、检索字符串中的字符串
在字符串中搜索指定值并返回匹配的位置:
indexOf() 和 search() 这两个方法,相等吗?
这两种方法并不相等。差别如下:
search() 方法不能接受第二个起始位置参数。
indexOf() 方法不能采用强大的搜索值(正则表达式)。
3、提取部分字符串
有三种提取部分字符串的方法:
- slice(start, end)
- substring(start, end)
- substr(start, length)
slice() 方法
slice() 提取字符串的某个部分并在新字符串中返回被提取的部分。该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。
这个例子裁剪字符串中位置 7 到位置 13 的片段:
var str = "Apple, Banana, Mango";var res = str.slice(7,13);
如果省略第二个参数,则该方法将裁剪字符串的剩余部分:
substring() 方法
substring() 类似于 slice()。
不同之处在于 substring() 无法接受负的索引。
var str = "Apple, Banana, Mango";var res = str.substring(7,13);
如果省略第二个参数,则该 substring() 将裁剪字符串的剩余部分。
substr() 方法
substr() 类似于 slice()。
不同之处在于第二个参数规定被提取部分的长度。
如果省略第二个参数,则该 substr() 将裁剪字符串的剩余部分。
var str = "Apple, Banana, Mango";var res = str.substr(7);
4、替换字符串内容
用另一个值替换在字符串中指定的值:
方法不会改变调用它的字符串。它返回的是新字符串。
默认地,replace() 只替换首个匹配,是对大小写敏感的
5、转换大小写
通过toUpperCase() 把字符串转换为大写:
通过 toLowerCase() 把字符串转换为小写:
6、concat()方法
concat() 连接两个或多个字符串:
var text1 = "Hello";var text2 = "World";
text3 = text1.concat(" ",text2);
所有字符串方法都会返回新字符串。它们不会修改原始字符串。
7、提取字符串字符
这是两个提取字符串字符的安全方法:
- charAt(position)
- charCodeAt(position)
charAt() 方法
charAt() 方法返回字符串中指定下标(位置)的字符串:
var str = "HELLO WORLD";
str.charAt(0); // 返回 H
charCodeAt() 方法
charCodeAt() 方法返回字符串中指定索引的字符 unicode 编码:
var str = "HELLO WORLD";
str.charCodeAt(0); // 返回 72
8、字符窜转换为数组
可以通过 split() 将字符串转换为数组:
includes() 方法
如果字符串包含指定值,includes() 方法返回 true。
检查字符串是否包含 "world",从位置 12 开始搜索:
let text = "Hello world, welcome to the universe.";
text.includes("world", 12) // 返回 false
startsWith() 方法
如果字符串以指定值开头,则 startsWith()方法返回true,否则返回false:
也可以指定开始检索的位置。
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello") // 返回 true
endsWith() 方法
如果字符串以指定值结尾,则 endsWith() 方法返回 true,否则返回 false:
用法和startsWith()方法一样。