Languages
[Edit]
EN

JavaScript - escape regular expression pattern special characters

10 points
Created by:
Mikolaj
309

In this short article, we would like to show how to escape special characters from pattern that we want to use with regular expression in JavaScript.

As the examples in the below, we will try to detext all .* occurances in the this is example text with .* and .* and .* text using different techniques (we will escape . and * charactes using different ways).

Practical example:

// ONLINE-RUNNER:browser;

const 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('.*');
const expression = new RegExp(pattern, 'g');

const text = 'this is example text with .* and .* and .*';
const result = text.match(expression);

console.log(pattern);  // '\.\*'
console.log(result);   // ['.*', '.*', '.*']

Hint: the above approach is useful when we want to escape all special characters automatically.

 

Manual escape

We can escape special characters manually by using \ or \\ before them.

1. Escape in string pattern

In strings we should escape special characters using \\.

// ONLINE-RUNNER:browser;

const expression = new RegExp('\\.\\*', 'g');

const text = 'this is example text with .* and .* and .*';
const result = text.match(expression);

console.log(result);   // ['.*', '.*', '.*']

2. Escape in syntax pattern

In syntax patterns we should escape special characters using \.

// ONLINE-RUNNER:browser;

const expression = /\.\*/g;

const text = 'this is example text with .* and .* and .*';
const result = text.match(expression);

console.log(result);   // ['.*', '.*', '.*']

 

Optimal solutions

1. Best performance

escapePattern() function is faster about 2.5x than replace based version.

// ONLINE-RUNNER:browser;

// 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('.*');
const expression = new RegExp(pattern, 'g');

const text = 'this is example text with .* and .* and .*';
const result = text.match(expression);

console.log(pattern);  // '\.\*'
console.log(result);   // ['.*', '.*', '.*']

1. Quite good performance:

escapePattern() function is faster about 1.5x than replace based version.

// ONLINE-RUNNER:browser;

const 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('.*');
const expression = new RegExp(pattern, 'g');

const text = 'this is example text with .* and .* and .*';
const result = text.match(expression);

console.log(pattern);  // '\.\*'
console.log(result);   // ['.*', '.*', '.*']

 

Alternative titles

  1. JavaScript - escape regular expression special characters
  2. JavaScript - escape RegExp special characters
  3. JavaScript - escape regex special characters
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join