node.js - 如何在正则表达式中使用 request.query
问题描述
我有这个搜索控制器,我想将其设置为检查搜索输入中的每个字母,但我不知道如何使用正则表达式。
module.exports.search = (req, res, next) => {
Character.find({
$or: [
{ firstName: req.query.search },
{ lastName: req.query.search }
]
})
.then(characters => {
res.status(200).send(characters);
})
.catch(next);
}
另外,我尝试过
{ firstName: /req.query.search/ }
,但它不起作用。任何帮助都会很棒。
解决方案
我找到了解决方案。我需要创建函数来放置整个正则表达式,然后在控制器内部将 req.query 传递给它
module.exports.search = (req, res, next) => {
if (req.query.search) {
const regex = new RegExp(escapeRegex(req.query.search), "gi");
Character.find({
$or: [{ firstName: regex }, { lastName: regex }]
})
.then(characters => {
res.status(200).send(characters);
})
.catch(next);
}
};
function escapeRegex(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
推荐阅读
- python-3.x - Python: subprocess.call('nvm ls', shell=True) 给出这个错误 /bin/sh: nvm: command not found
- list - 如何将数据数组转换为在颤振/飞镖中展开或折叠的小部件列表?
- visual-studio-2017 - 从 Visual Studio 2017 Pro 迁移到社区版
- webstorm - 无法将 WSL 节点解释器添加到 WebStorm
- javascript - .push() 覆盖 Javascript 中的数组值
- sql - 最小和最大游戏数之间的差异
- julia - 如何在 Julia 中限制数组的列
- javascript - 我的自动段落幻灯片不起作用
- jquery - 什么时候应该使用 jQuery.each() 而不是 _.each() (http://underscorejs.org/)?什么时候应该使用 _.each() 而不是 jQuery.each()?
- uwp - 在 DataTemplate UWP 中绑定 ComboBoxItem 的 IsSelected 属性