Note: there was a similar question but since it didn't have 'Special characters' and the problem here is only with 'Special characters', I posted a new question.
I have a list (from user input textarea) of Regular Expression representations:
Example: (simplified)
// starting point is a string like this one
let str = `/ab+c/
/Chapter (\d+)\.\d*/
/\d+/
/d(b+)d/`;
I need to convert them into an array to check (for validity) and prepare each line e.g. (simplified)
let arr = str.split(/[\r\n]+/);
for (let i = 0, len = arr.length; i < len; i++) {
arr[i] = arr[i].slice(1, -1); // removing the start/end slashes
// problem with double slashing the Special characters
// it doesn't give the required result
arr[i] = arr[i].replace(/\\/g, '\\$&');
// same result with replace(/\\/g, '\\\\')
}
Finally, convert them into one RegEx object
let regex = new RegExp(arr.join('|'), 'i');
console.log(regex.test('dbbbd')); // true
console.log(regex.test('256')); // false
I must be missing something here.
Update
I missed the point that the data that comes from a textarea (or similar) doesn't need to be escaped at all. When I was testing the code, I was testing it like above which didn't work.
/\d+/.toString();or use type coercion likemyRegExpObj + ""and then perform string operations.new RegExp()doesn’t need double \ if you actually want the regular expression meaning (e.g\dfor digits). It’s the string literal that needs it, because \ is used there for some escape sequences such as\nand quite a few more. Do in your original code, you should have \\ in the string, but not manipulate it afterwards. If the regex comes from somewhere else (HTML input, JSON...) then you don’t need to do anything at all.