如何在JavaScript中检查字符串是否包含子字符串

Checking if a string contains a substring is one of the most common tasks in any programming language.

在任何编程语言中,检查字符串是否包含子字符串是最常见的任务之一。

JavaScript offers different ways to perform this operation.

JavaScript提供了执行此操作的不同方法。

The most simple one, and also the canonical one going forward, is using the includes() method on a string:

最简单的方法,以及随后的规范方法,都是在字符串上使用includes()方法:

'a nice string' . includes ( 'nice' ) //true

This method was introduced in ES6/ES2015.

此方法已在ES6 / ES2015中引入。

It’s supported in all modern browsers except Internet Explorer:

除Internet Explorer之外,所有现代浏览器均支持该功能:

浏览器支持包括

To use it on all browsers, use Polyfill.io or another dedicated polyfill.

要在所有浏览器上使用它,请使用Polyfill.io或其他专用的polyfill。

includes() also accepts an optional second parameter, an integer which indicates the position where to start searching for:

includes()还接受可选的第二个参数,该整数表示开始搜索的位置:

'a nice string' . includes ( 'nice' ) //true
  'a nice string' . includes ( 'nice' , 3 ) //false
  'a nice string' . includes ( 'nice' , 2 ) //true

ES6之前的替代include(): indexOf() (Pre-ES6 alternative to includes(): indexOf())

Pre-ES6, the common way to check if a string contains a substring was to use indexOf, which is a string method that return -1 if the string does not contain the substring. If the substring is found, it returns the index of the character that starts the string.

在ES6之前,检查字符串是否包含子字符串的常用方法是使用indexOf ,这是一个字符串方法,如果该字符串不包含子字符串,则返回-1。 如果找到了子字符串,它将返回以字符串开头的字符的索引。

Like includes(), the second parameters sets the starting point:

includes() ,第二个参数设置起点:

'a nice string' . indexOf ( 'nice' ) !== - 1 //true
  'a nice string' . indexOf ( 'nice' , 3 ) !== - 1 //false
  'a nice string' . indexOf ( 'nice' , 2 ) !== - 1 //true

翻译自: https://flaviocopes.com/how-to-string-contains-substring-javascript/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值