String.prototype.includes() - JavaScript 编辑

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Syntax

str.includes(searchString[, position])

Parameters

searchString
A string to be searched for within str.
position Optional
The position within the string at which to begin searching for searchString. (Defaults to 0.)

Return value

true if the search string is found anywhere within the given string; otherwise, false if not.

Description

This method lets you determine whether or not a string includes another string.

Case-sensitivity

The includes() method is case sensitive. For example, the following expression returns false:

'Blue Whale'.includes('blue')  // returns false

Polyfill

This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet.

However, you can easily polyfill this method:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';

    if (search instanceof RegExp) {
      throw TypeError('first argument must not be a RegExp');
    }
    if (start === undefined) { start = 0; }
    return this.indexOf(search, start) !== -1;
  };
}

Examples

Using includes()

const str = 'To be, or not to be, that is the question.'

console.log(str.includes('To be'))        // true
console.log(str.includes('question'))     // true
console.log(str.includes('nonexistent'))  // false
console.log(str.includes('To be', 1))     // false
console.log(str.includes('TO BE'))        // false
console.log(str.includes(''))             // true

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'String.prototype.includes' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:75 次

字数:5370

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文