JavaScript regex escape multiple characters

前端 未结 2 454
遥遥无期
遥遥无期 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:16

    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}`)); // "/\&\&|\|\|/"

提交回复
热议问题