JavaScript regex escape multiple characters

前端 未结 2 445
遥遥无期
遥遥无期 2021-01-20 05:34

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

const _and = \'&&\', _or = \'||\';
let re         


        
2条回答
  •  失恋的感觉
    2021-01-20 06:12

    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
    

提交回复
热议问题