Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex escape multiple characters

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.

like image 493
Kristupas Repečka Avatar asked Mar 03 '26 10:03

Kristupas Repečka


1 Answers

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
like image 67
kamyl Avatar answered Mar 05 '26 23:03

kamyl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!