js escape regex pattern characters
JavaScript[Edit]
+
0
-
0
js escape regex pattern characters
1 2 3 4 5 6 7 8 9 10 11 12 13 14const SPECIAL_CHARACTERS_EXPRESSION = /([.*+?^=!:${}()|\[\]\/\\])/g; // Escapes regular expression pattern special characters in the indicated string. // const escapePattern = (pattern) => { return pattern.replace(SPECIAL_CHARACTERS_EXPRESSION, '\\$1'); }; // Usage example: const pattern = escapePattern('.*'); console.log(pattern); // '\.\*'
[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); // '\.\*'
[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 19const SPECIAL_CHARACTERS = { '^': 1, '$': 1, '*': 1, '+': 1, '?': 1, '.': 1, '{': 1, '}': 1, '(': 1, ')': 1, '[': 1, ']': 1, '=': 1, ':': 1, '!': 1, '|': 1, '/': 1, '\\': 1 }; // 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]; result += (SPECIAL_CHARACTERS[entry] ? '\\' + entry : entry); } return result; }; // Usage example: const pattern = escapePattern('.*'); console.log(pattern); // '\.\*'
[Edit]
+
0
-
0
js escape regex pattern characters
1 2 3 4 5const expression = new RegExp('\\.\\*', 'g'); // where: \\ will be converted to \ in the string literal // . escaped by \. and * escaped by \* // Topic: https://dirask.com/questions/JavaScript-why-in-string-value-should-I-use-to-get-and-in-read-file-only-double-backslashes-in-strings-1b6xJ1 console.log(expression.source); // '\\.\\*' <---- source returns string literals with changed \ to \\
[Edit]
+
0
-
0
js escape regex pattern characters
1 2 3const expression = /\.\*/g; // . escaped by \. and * escaped by \* console.log(expression.source); // '\\.\\*' <---- source returns string literals with changed \ to \\