indexof方法_JavaScript中indexOf()和search()方法之间的区别

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.


翻译自: https://www.includehelp.com/code-snippets/difference-between-indexOf-and-search-methods-in-javascript.aspx

indexof方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值