3

Is is possible escape parameterized regex when parameter contains multiple simbols that need to be escaped?

const _and = '&&', _or = '||';
let reString = `^(${_and}|${_or})`; //&{_or} needs to be escaped
const reToken = new RegExp(reString);

Working but not optimal:

_or = '\\|\\|';

Or:

let reString = `^(${_and}|\\|\\|)`;

It is preferred to reuse _or variable and keep regex parameterized.

  • Btw. you can use `and` and `or` names for variables, as these in javascript aren't [reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords). No need to add `_` prefix, which some people add to private properties names. Not saying that you should, but you definitely can. :) – kamyl Aug 21 '17 at 16:43
  • Yup. Thank you. I guess it's mental consequence of having python backend :)) – Kristupas Repečka Aug 21 '17 at 18:08

2 Answers2

2

EDITED https://jsfiddle.net/ao4t0pzr/1/

You can use a Template Literal function to escape the characters within the string using a Regular Expression. You can then use that string to propagate a new RegEx filled with escaped characters:

    function escape(s) {
        return s[0].replace(/[-&\/\\^$*+?.()|[\]{}]/g, '\\$&');
    };
    
    var or = escape`||`;
    var and = escape`&&`;
    console.log(new RegExp(`${and}|${or}`)); // "/\&\&|\|\|/"
Toto
  • 89,455
  • 62
  • 89
  • 125
zfrisch
  • 8,474
  • 1
  • 22
  • 34
2

You can make your own function which would escape your parameters, so that these works in final regexp. To save you time, I already found one written in this answer. With that function, you can write clean parameters without actually escaping everything by hand. Though I would avoid modifying build in classes (RegExp) and make a wrapper around it or something separate. In example below I use exact function I found in the other answer, which extends build in RegExp.

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

const and = RegExp.escape('&&');
const or = RegExp.escape('||');

const andTestString = '1 && 2';
const orTestString = '1 || 2';
const regexp = `${and}|${or}`;

console.log(new RegExp(regexp).test(andTestString)); // true
console.log(new RegExp(regexp).test(orTestString)); // true
kamyl
  • 5,938
  • 4
  • 23
  • 29