0

I have the following code to filter a list based on what the user types in an input field:

const searchQuery = e.target.value.trim();

items
  .filter((item) =>
    item.title.match(new RegExp(searchQuery, 'gi'))
  )
  .map(item => {
    // Do something...
  });

it works great except everything breaks when the user enters some funky text in the input field like:

//on\/: \/: \

Results in the following error:

SyntaxError: Invalid regular expression: ///on\/: \/: \/: \ at end of pattern

How to approach this correctly so that my code doesn't break based on user input?

  • if you want to allow for a regex in the input then you have to let the user know if the regex is wrong, otherwise you need to create a regex based on general user input urself by prepending and appending to the input – MozenRath Dec 04 '19 at 20:19
  • @MozenRath I don't want to allow the user to enter REGEX, I just want to prevent my code form breaking if they do (either on purpose or by accident). So I guess I want to know how to "escape" the user's input if that's the right word. –  Dec 04 '19 at 20:25
  • 1
    https://stackoverflow.com/questions/16434174/only-allow-certain-characters-to-be-entered-in-html-textinput – Jason Owens Dec 04 '19 at 20:25
  • 1
    hope this helps: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex – MozenRath Dec 04 '19 at 20:30
  • How can this be a duplicate of a duplicate ? –  Dec 04 '19 at 20:33

1 Answers1

0

Sounds like you need to perform escapes, or some type of validation. Here's a link to the JavaScript escape() Function. I hope that helps.

Jason Owens
  • 525
  • 2
  • 6
  • 21