0

I have a function which sorts the data based on the value given in the input but when user enter backslash \ it's breaking down. How do I escape it.

https://jsfiddle.net/48axs3gd/

<input type="text" onblur="getSortedData(this.value)">

function getSortedData(value) {
 console.log("value", value)
      const regex = new RegExp(value, "i");
  };
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • can you post your full code? – Kaushik May 10 '19 at 04:44
  • 1
    It fails only if backslash is the last character, because the expectation is that you'd want something escaped but there is nothing there. if you have more characters after it, it becomes a valid pattern, e.g. `ab\d` . But you have a bigger problem because it's not *just* backslash - you can have a ton of invalid patterns with this. For example starting with `*` would lead to an error for any pattern after it because there is nothing to quantify. What are you even trying to do? If you want people to enter a regex, you may allow them to enter invalid ones. Otherwise, sanitise the input. – VLAZ May 10 '19 at 05:05
  • You may want to check out this question: https://stackoverflow.com/questions/17250815/how-to-check-if-the-input-string-is-a-valid-regular-expression - it relates to what VLAZ said about any invalid regex being a problem. – jimf May 10 '19 at 06:29
  • @jimf that's definitely one step you could take but I think it's more important to step back and think about what's supposed to be accomplished here. This will influence what the solution would be. After all, what do you even do if somebody enters `*abc`? Escape `*` to treat it as literal? Clear the entire input and make people enter it again? Stealthily correct `*` to `.*` to make it behave like the `*` wildcard in other places? Should that also be done for `*` anywhere else in the input? Lots of solutions, not clear which is the correct one. Maybe a regex isn't even needed. – VLAZ May 10 '19 at 06:55
  • You should always escape literal regex parts before using in the `RegExp` constructor. – Wiktor Stribiżew May 10 '19 at 09:35

0 Answers0