JS

您所在的位置:网站首页 jquery字符串包含 JS

JS

2024-07-11 01:03| 来源: 网络整理| 查看: 265

JS-判断字符串中包含指定字符 Eva 2019.6.25 于天津 1、使用includes()方法-ES62、使用indexOf()方法-ES5或更老的版本3、正则表达式-test()4、正则表达式-match()

Eva 2019.6.25 于天津 1、使用includes()方法-ES6

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

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

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

3、正则表达式-test()

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

4、正则表达式-match()

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

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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3