当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


JavaScript String indexOf()用法及代码示例


字符串 indexOf() 方法

indexOf() is method 是一个 String 方法,用于检查给定字符串中是否存在子字符串。它从子字符串所在的字符串返回子字符串的起始索引。如果字符串中不存在子字符串 – 则返回 -1。

用法:

    String.indexOf(substring, [offset]);

这里,substring是要搜索的字符串的一部分,并且[offset]是我们要搜索子字符串的特定索引,它是一个可选参数,默认值为 0。

例:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
<script>		
	var str = "IncludeHelp is for programmers";
	
	var substr = "is";		
	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>");

	substr = "Hello";
	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>");
	
	//searching from a specific index
	substr = "is";
	index = str.indexOf(substr,10);		
	if(index!=-1)
		document.write(substr + " found at " + index + " position.<br>");
	else
		document.write(substr + " does not exist in the " + str + ".<br>");		

	substr = "is";
	index = str.indexOf(substr,20);		
	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>

输出

is found at 12 position.
Hello does not exist in the IncludeHelp is for programmers.
is found at 12 position.
is does not exist in the IncludeHelp is for programmers.



相关用法


注:本文由纯净天空筛选整理自 String indexOf() Method with Example in JavaScript。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。