lastindexof方法_字符串lastIndexOf()方法,带有JavaScript中的示例

lastindexof方法

字符串lastIndexOf()方法 (String lastIndexOf() Method)

lastIndexOf() is method is a String method, it is used to check whether a substring exists in the given string or not. It returns the last index of the substring from the string where substring exists. If substring does not exist in the string – it returns -1.

lastIndexOf()是一个String方法,用于检查给定字符串中是否存在子字符串。 它从存在子字符串的字符串中返回子字符串的最后一个索引。 如果字符串中不存在子字符串,则返回-1

Syntax:

句法:

    String.lastIndexOf(substring, [offset]);

Here, substring is the part of the string to be searched and [offset] is the specific index from where we want to search the substring, it's an optional parameter and it's default value is 0.

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

Note: Method lastIndexOf() searches backward in the string, see in the example – we passed offset 15 and it returns index 0.

注意: 方法lastIndexOf()在字符串中向后搜索,请参见示例–我们传递了偏移量15并返回索引0。

Example:

例:

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

<body>
<script>		
	var str = "Hello friends say Hello";
	
	var substr = "Hello";		
	var index = str.lastIndexOf(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.lastIndexOf(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 = "Hello";
	index = str.lastIndexOf(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 = "friends";
	index = str.lastIndexOf(substr,15);		
	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 18 position.
Hi does not exist in the Hello friends say Hello.
Hello found at 0 position.
friends found at 6 position.


翻译自: https://www.includehelp.com/code-snippets/string-lastIndexOf-method-with-example-in-javascript.aspx

lastindexof方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值