Escaping RegExp string

Sometimes we need to match special RegExp characters such as ? and + in our string. We can conveniently use the function below.


function escapeRegex(string) {
  return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

console.log("C A++".match(new RegExp(escapeRegex("A+"))));

["A+", index: 2, input: "C A++", groups: undefined]