1// Vanilla JS
2function escapeRegex(string) {
3 return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4}
5
6// Or with npm: npm install escape-string-regexp
7const escapeRegex = require('escape-string-regexp');
8
9// Usage:
10const regex = new RegExp(escapeRegex('How much $ is that?'));
1function escapeRegExp(input) {
2 const source = typeof input === 'string' || input instanceof String ? input : '';
3 return source.replace(/[-[/\]{}()*+?.,\\^$|#\s]/g, '\\$&');
4}
5