字符串中判断是否包含某个字符

一、方法一:new RegExp

1、概述: RegExp 是正则表达式的缩写;
当检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp 就是这种模式

2. RegExp对象的方法

1) RegExp 对象有 3 个方法:test()、exec() 以及 compile();

test()
  • test() 方法检索字符串中的指定值。返回值是 true 或 false;
        let b = new RegExp('f')
        console.log(b.test('abdcfa')) //true

     

exec()
  • exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null;
        let b = new RegExp('f')
        console.log(b.exec('abdcfaff dlfja'))

     

  • 在exec()方法中,可以向 RegExp 对象添加第二个参数,以设定检索。例如,如果需要找到所有某个字符的所有存在,则可以使用 “g” 参数 (“global”);
    在使用 “g” 参数时,exec() 的工作原理如下:
    1> 找到第一个 “e”,并存储其位置;
    2> 如果再次运行 exec(),则从存储的位置开始检索,并找到下一个 “e”,并存储其位置;

  •     let b = new RegExp('a','g')
        let c = null
        let d = []
        do
        {
          c = b.exec('abca')
          console.log(c) // ['a', index: 0, input: 'abca', groups: undefined]
          let obj = {}
          obj =  {...obj,...c} // 老的写法:Object.assign({},c)
          console.log(obj) // {0: 'a', index: 0, input: 'abca', groups: undefined}
          d.push(obj)
        }
        while(c !== null)
        console.log(d) // [{0: 'a', index: 0, input: 'abca', groups: undefined},{0: 'a', index: 3, input: 'abca', groups: undefined},{}]

     

     

compile()
  • compile() 方法用于改变 RegExp。compile() 既可以改变检索模式,也可以添加或删除第二个参数;
  •     let e = new RegExp('a')
        console.log(e.test('jfjdlfa'))//true
        e.compile('b')
        console.log(e.test('jfjdlfa'))//false

     

参考:

https://www.cnblogs.com/yejt/p/16201814.html

posted @ 2022-09-19 10:27  最爱小虾  阅读(3814)  评论(0编辑  收藏  举报