[Edit]
+
0
-
0

js escape regex pattern characters

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// Hint: it is most optimal way to escape patterns represent as strings. // Escapes regular expression pattern special characters in the indicated string. // const escapePattern = (pattern) => { let result = ''; for (let i = 0; i < pattern.length; ++i) { const entry = pattern[i]; switch (entry) { case '^': case '$': case '*': case '+': case '?': case '.': case '{': case '}': case '(': case ')': case '[': case ']': case '=': case ':': case '!': case '|': case '/': case '\\': result += '\\' + entry; break; default: result += entry; break; } } return result; }; // Usage example: const pattern = escapePattern('.*'); console.log(pattern); // '\.\*'