1

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.

const lowercaseName = new RegExp(`^${name}`, 'i')
const songs: any = await Song.find({ name: lowercaseName, artist_id })
NeNaD
  • 18,172
  • 8
  • 47
  • 89
unicorn_surprise
  • 951
  • 2
  • 21
  • 40
  • 1
    Does this answer your question? [Is there a RegExp.escape function in JavaScript?](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) – skara9 Jan 27 '22 at 00:45

1 Answers1

1

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 })
NeNaD
  • 18,172
  • 8
  • 47
  • 89