在开发过程中,很多时候我们有在一个 字符串 中查找另一个字符串或者字符的需求,在 JavaScript 中,在一个字符串中查找另一个字符串有四种方法,分别为:使用 indexOf 函数、使用 lastIndexOf 函数、使用 match 函数和使用 search 函数。
indexOf() 方法可 返回 某个指定的字符串在源字符串中首次出现的位置。
stringObject.indexOf(searchvalue,fromindex)
参数 | 描述 |
---|---|
searchvalue | 必需。规定需检索的字符串值。 |
fromindex | 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。 |
返回 searchvalue 的第一次出现的位置,如果没找到,则返回 -1。
该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。
lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。
stringObject.lastIndexOf(searchvalue,fromindex)
参数 | 描述 |
---|---|
searchvalue | 必需。规定需检索的字符串值。 |
fromindex | 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的最后一个字符处开始检索。 |
如果在 stringObject 中的 fromindex 位置之前存在 searchvalue,则返回的是出现的最后一个 searchvalue 的位置。
该方法将从尾到头地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置在字符串的 fromindex 处或字符串的结尾(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一个字符在 stringObject 中的位置。
使用 indexOf 函数,查找字符串
<!DOCTYPE html>
<html>
<head>
<title>JavaScript indexOf查找字符串</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var strHaiCoder = "I love Golang and I study Golang From HaiCoder"
var index = strHaiCoder.indexOf("I");
console.log("Index =", index);
var index2 = strHaiCoder.indexOf("love");
console.log("Index2 =", index2);
var index3 = strHaiCoder.indexOf("haicoder");
console.log("Index3 =", index3);
</script>
</head>
</html>
程序运行后,控制台输出如下:
首先,我们定义了一个字符串类型的 变量 strHaicoder,接着我们使用字符串的 indexOf() 函数查找字符串变量 strHaicoder 中单个字符 l
首次出现的位置,并打印最终的结果。字符 I
在变量 strHaicoder 中第一次出现在了第一个位置,所以返回了 0。
接着,我们再次使用 indexOf 函数查找字符串 “love” 在字符串中出现的位置,结果返回了 2。
最后,我们使用 indexOf 函数查找不存在的字符串 “haicoder” 在字符串中出现的位置,因为字符串 “haicoder” 不存在字符串中,因此返回了 -1。
使用 lastIndexOf 函数,查找字符串
<!DOCTYPE html>
<html>
<head>
<title>JavaScript lastIndexOf查找字符串</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var strHaiCoder = "I love Golang and I study Golang From HaiCoder"
var index = strHaiCoder.lastIndexOf("I");
console.log("Index =", index);
var index2 = strHaiCoder.lastIndexOf("love");
console.log("Index2 =", index2);
var index3 = strHaiCoder.lastIndexOf("haicoder");
console.log("Index3 =", index3);
</script>
</head>
</html>
程序运行后,控制台输出如下:
使用 lastIndexOf 函数,从后往前查找指定的字符串。
在 JavaScript 中,在一个字符串中查找另一个字符串有四种方法,分别为:使用 indexOf 函数、使用 lastIndexOf 函数、使用 match 函数和使用 search 函数。