indexof方法
Prerequisite:
先决条件:
Though indexOf() and search() both methods are used to check whether a substring exists in the string or not and returns either of the index of the substring or -1 (if substring does not exist in the string), there is a difference between indexOf() and search() methods. Consider the syntaxes of both methods:
尽管indexOf()和search()两种方法都用于检查字符串中是否存在子字符串,并返回子字符串的索引或-1(如果字符串中不存在子字符串), 则存在区别在indexOf()和search()方法之间 。 考虑这两种方法的语法:
Syntax of indexOf() method:
indexOf()方法的语法:
String.indexOf(substring, [offset]);
Syntax of search() method:
search()方法的语法:
String.search(substring);
Now, you can clearly see that in indexOf() method, there is an optional parameter(offset) from where we can start the searching but the method search() does not have this feature. It simply takes the substring and starts searching from the 0th index.
现在,您可以清楚地看到,在indexOf()方法中,有一个可选的参数(偏移),从此处可以开始搜索,但是方法search()没有此功能。 它只是获取子字符串并从第0 个索引开始搜索。
Example:
例:
<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
var str = "friends say Hello";
var substr = "Hello";
var index = str.indexOf(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
var substr = "Hello";
var index = str.search(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
substr = "Hi";
index = str.indexOf(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
substr = "Hi";
index = str.search(substr);
if(index!=-1)
document.write(substr + " found at " + index + " position.<br>");
else
document.write(substr + " does not exist in the " + str + ".<br>");
</script>
</body>
</html>
Output
输出量
Hello found at 12 position.
Hello found at 12 position.
Hi does not exist in the friends say Hello.
Hi does not exist in the friends say Hello.
indexof方法