In the development of express website, I use mongoose to do full-text search, the code is as follows:
var keywords = req.query.keywords;
Article.find().where('content').equals(new RegExp(keywords, 'i'));
This can be retrieved normally in most cases, but if keywords contain Chinese characters, for example:
Var keywords =' stomach wants to eat';
Article.find().where('content').equals(new RegExp(keywords, 'i'));
At this time, you will not be able to find mongoose information that contains “belly wants to eat” in the content.
What can I do to make keywords with white space search normally?
In general, the space symbol in the search keyword represents a separator, which separates the query content into multiple keywords, namely
Key words:belly
Represents searching for belly-related content
Key words:My stomach wants to eat
On behalf of the search includes both belly and want to eat contentFirst of all, you have to find out what you want to search for
ContainMy stomach wants to eat
The content of
Or does it include bothbelly
AndWant to eat
The content ofYou
new RegExp(keywords, 'i')
This code is definitely problematic. What if keywords contain regular keywords?I found a regular one on the internet, you can try it.
/(? =.? aa)(? =.? Bb)/mg match contains both aa and bbEscape keywords including
^$()*+? .|[]{}new RegExp('12$31]23^'.replace(/([\^\$\(\)\*\+\? \.\\\|\[\]\{\}])/g, "\\$1"), 'g').test('12312312312$31]23^asdasd') true new RegExp('12$31]23^', 'g').test('12312312312$31]23^asdasd') false var keyword = '12$31]23^'; //Escape regular keywords keyword = keyword.replace(/([\^\$\(\)\*\+\? \.\\\|\[\]\{\}])/g, "\\$1"); new RegExp(keyword, 'mg')