diff --git a/README.md b/README.md index 0a64be235..12b807a8e 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ * [Curry](#curry) * [Difference between arrays](#difference-between-arrays) * [Distance between two points](#distance-between-two-points) +* [Escape regular expression](#escape-regular-expression) * [Even or odd number](#even-or-odd-number) * [Factorial](#factorial) * [Fibonacci array generator](#fibonacci-array-generator) @@ -120,6 +121,16 @@ var distance = x0, y0, x1, y1 => Math.sqrt(Math.pow(x1-x0, 2) + Math.pow(y1 - y0, 2)) ``` +### Escape regular expression + +Use `replace()` to escape special characters. + +```js +escapeRegExp = s => + s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} +``` + ### Even or odd number Use `Math.abs()` to extend logic to negative numbers, check using the modulo (`%`) operator. diff --git a/snippets/escape-regular-expression.md b/snippets/escape-regular-expression.md new file mode 100644 index 000000000..b653c066d --- /dev/null +++ b/snippets/escape-regular-expression.md @@ -0,0 +1,9 @@ +### Escape regular expression + +Use `replace()` to escape special characters. + +```js +escapeRegExp = s => + s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} +```