在 JavaScript 中检查字符串是否包特定字符串

发布于 2022-07-29 00:22:28 字数 2515 浏览 159 评论 0

在 JavaScript 中有两种常用的方法来检查字符串是否包含子字符串。 更现代的方式是 String#includes() 功能

const str = 'Arya Stark';

str.includes('Stark'); // true
str.includes('Snow'); // false

您可以使用 String#includes() 在所有现代浏览 除了 Internet Explorer 中。 你也可以使用 String#includes() 在 Node.js 中 >= 4.0.0

兼容性表 Mozilla 开发者网络

如果您需要支持 Internet Explorer,则应改为使用 String#indexOf()方法 ,自 1997 年 ES1 以​​来一直是 JavaScript 的一部分。

const str = 'Arya Stark';

str.indexOf('Stark') !== -1; // true
str.indexOf('Snow') !== -1; // false

一般来说,如果您对代码是否会在支持 includes(),你应该使用 indexOf()。这 includes() 函数的语法比 indexOf()

不区分大小写的搜索

两个都 String#includes()String#indexOf()区分大小写。 这两个函数都不支持正则表达式。 要进行不区分大小写的搜索,您可以使用正则表达式和 String#match() 函数 ,或者您可以使用 String#toLowerCase() 功能

const str = 'arya stark';

// The most concise way to check substrings ignoring case is using
// `String#match()` and a case-insensitive regular expression (the 'i')
str.match(/Stark/i); // true
str.match(/Snow/i); // false

// You can also convert both the string and the search string to lower case.
str.toLowerCase().includes('Stark'.toLowerCase()); // true
str.toLowerCase().indexOf('Stark'.toLowerCase()) !== -1; // true

str.toLowerCase().includes('Snow'.toLowerCase()); // false
str.toLowerCase().indexOf('Snow'.toLowerCase()) !== -1; // false

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

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

发布评论

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

关于作者

誰認得朕

暂无简介

0 文章
0 评论
22 人气
更多

推荐作者

yangzhenyu123

文章 0 评论 0

lvzun

文章 0 评论 0

执笔绘流年

文章 0 评论 0

芯好空

文章 0 评论 0

始于初秋

文章 0 评论 0

谁与争疯

文章 0 评论 0

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