0

I am trying to write a regex expression that will test if a given string has the following:

  • single quote
  • double quotes
  • forward slash
  • back slash

The string will be eventually coming from a JSON object.

here's what I have put together for testing purposes:

const validationRegex = new RegExp('[\'\"\\\/]+', 'g');
const name = `
myname\
`

let result = validationRegex.test(name)
console.log(result)

The result is "true" for the single quote, double quotes and forward slash which is the expected behavior. However for back slashes result is "false"

e.g.

const validationRegex = new RegExp('[\'\"\\\/]+', 'g');
const name = `
myname\
`

let result = validationRegex.test(name)
console.log(result) // false

What am I missing?

Fouad
  • 855
  • 1
  • 11
  • 30
  • The `\\\/` part matches a single `/`. Use 4 backslashes in a constructor notation. Or declare with a regex literal - `validationRegex = /['"\\\/]/g` – Wiktor Stribiżew Aug 03 '17 at 11:10
  • @Wiktor that didn't work – Fouad Aug 03 '17 at 20:18
  • You want to get `false` if a string contains one of these symbols inside `[...]`, right? So, you may use `/['"\\\/]/.test("name\\")` will return *false* because `"name\\"` string literal defines a literal string ``name\`` – Wiktor Stribiżew Aug 03 '17 at 20:23

0 Answers0