How to ignore a string if contains certain match using RegExp

This article was published on May 15, 2021, and takes approximately a minute to read.

In my CMS, I wanted to disallow any string which contains double quote " for certain fields.

Luckily it allows me pass a Regex to valid it. To do that I needed to:

^((?!").)*$

where:

  • ^ matches the begining of the string;
  • $ matches the end of the the string;
  • (?!") is a negative lookahead, in other words, it matches double quotes but negate it (don't pick up);
  • ( .)* matches everything else except the previous match (double quote)

So if I type double quote in my field, it won't allow me because the regex returns false:

var first = 'hey you';
var second = 'what can I do "for you"';

var regex = /^((?!").)*$/gim;

console.log(first.match(regex)); // ["hey you"]
console.log(second.match(regex)); // null <- not valid