uni-app小程序不支持new RegExp的模糊查询

uni-app小程序不支持new RegExp的模糊查询

产品分类:uniCloud/App

操作步骤:

预期结果:

实际结果:

bug描述:

想写一个搜索的功能,数据写在uniCloud中,app测试可以正确查询到,小程序不支持该方法,有什么解决办法嘛?

图片

Image 1 Image 2 Image 3 Image 4


更多关于uni-app小程序不支持new RegExp的模糊查询的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

小程序不能在属性内传递RegExp,建议改成字符串的形式

更多关于uni-app小程序不支持new RegExp的模糊查询的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app小程序中使用new RegExp进行模糊查询确实会遇到兼容性问题,因为小程序环境对JavaScript的RegExp支持有限。针对你的搜索功能需求,这里提供几种可行的解决方案:

  1. 使用数据库查询操作符(推荐) 在uniCloud的云函数中,使用数据库操作符实现模糊查询:

    const db = uniCloud.database()
    const result = await db.collection('yourCollection')
      .where({
        fieldName: new RegExp(searchText) // 云函数中可用
      })
      .get()
    
  2. 使用$regex操作符 如果需要在客户端直接查询,可以使用MongoDB的$regex操作符:

    const db = uniCloud.database()
    const result = await db.collection('yourCollection')
      .where({
        fieldName: {
          $regex: searchText,
          $options: 'i' // i表示不区分大小写
        }
      })
      .get()
    
  3. 客户端过滤 先获取数据到本地,然后用JavaScript的字符串方法过滤:

    const allData = await db.collection('yourCollection').get()
    const filteredData = allData.data.filter(item => 
      item.fieldName.includes(searchText)
    )
    
  4. 使用云函数封装 将查询逻辑放到云函数中,小程序端调用云函数:

    // 云函数
    exports.main = async (event) => {
      const { searchText } = event
      return await db.collection('yourCollection')
        .where(new RegExp(searchText))
        .get()
    }
回到顶部