回答

收藏

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

技术问答 技术问答 527 人阅读 | 0 人回复 | 2023-09-11

通常我会期待一个String.contains()方法,但似乎没有。1 N4 [/ Z" u, N  k) T2 [
检查这一点的合理方法是什么?8 Z8 `+ D: G7 P9 c8 ]) ?0 C6 w
                                                               
8 M0 B# A, G, f5 e! O" ]    解决方案:                                                               
1 U4 V) X. @$ b' e5 A" I                                                                ECMAScript 6 引入String.prototype.includes:
" C1 s4 X- s: Y; j7 ~/ H
    const string = "foo";const substring = "oo";console.log(string.includes(substring)); // true
    $ k, Z, c- B' m& X0 b
includes但没有 Internet Explorer 支持ECMAScript 在5 或更旧的环境中使用String.prototype.indexOf,找不到子字符串时返回 -1:5 G# O3 c. ]# n1 V  N
    var string = "foo";var substring = "oo";console.log(string.indexOf(substring) !== -1); // true
    7 F# ?. e7 g6 M
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则