Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB RegEx not finding any results when string contains parenthesis

When using regex to allow for case insensitivity, it only works for plain strings. The db query returns no results when parenthesis or other special characters are used for the name.

Example: "Push It" will work fine and return songs. However when searching "Escape (The Pina Colada Song)", it returns no songs. How can I make the Regex allow for these special characters?

Any suggestions would be great.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const lowercaseName = new RegExp(`^${name}`, 'i')
const songs: any = await Song.find({ name: lowercaseName, artist_id })

>Solution :

You should escape all the special characters in the string that you are sending. Try this:

const lowercaseName = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, 'i')
const songs: any = await Song.find({ name: lowercaseName, artist_id })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading