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之外,所有现代浏览器均支持该功能:
![浏览器支持包括](https://flaviocopes.com/how-to-string-contains-substring-javascript/browser-support-includes.png)
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/