JS-判断字符串中包含指定字符

时间:2025-02-07 08:25:32

JS-判断字符串中包含指定字符

    • Eva 2019.6.25 于天津
  • 1、使用includes()方法-ES6
  • 2、使用indexOf()方法-ES5或更老的版本
  • 3、正则表达式-test()
  • 4、正则表达式-match()

Eva 2019.6.25 于天津

1、使用includes()方法-ES6

includes()方法是ES6中引入的,但需要注意的是不支持IE浏览器
代码实现
var str = “let’s test”,
subStr = “test”;
(subStr);
运行结果
true

2、使用indexOf()方法-ES5或更老的版本

indexOf()方法返回符合指定字符串首位下标,当字符串中不包含指定字符串时返回-1.
代码实现
var str = “let’s test again”,
subStr = “again”;
(subStr);
运行结果
11

3、正则表达式-test()

正则表达式更灵活,更方便。不存在不兼容的情况,RegExp#test()。
代码实现
var str = “let’s test again”,
reg = /again/;
(str);
运行结果
true

4、正则表达式-match()

正则表达式更灵活,更方便。不存在不兼容的情况,RegExp#match()。
代码实现
var str = “let’s test again”,
reg = /again/;
(reg);
运行结果
[“again”]
注意,若没有匹配的字符串,那么返回null。

注意
如果字符串为null时,方法一和方法二会报错,TypeError: null is not an object。大家根据实际情况选择合适的方法。