I have found this and this, that demonstrate how to escape reserved regex characters in string literals.
My Code
function escapeRegExp2(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
const str0 = 'some me ome \*me \w*me mee';
const str1 = '\*me';
const cleanStr1 = escapeRegExp2(str1);
const regex = new RegExp(cleanStr1, 'i');
console.log(`str0.match(regex): ${str0.match(regex)}`);
If you look at the output, match()
returns *me
, as opposed to \*me
. In other words it leaves out the backslash character, which was purposefully included.
How do I ensure all characters are included in match/search
while still escaping malicious code?
Edit
After comments, I have made a simplified example:
const str0 = 'some me ome \\*me \\w*me mee';
const str1 = '\\*me';
console.log(`Match: ${str0.match(str1)}`);
Should it not look for the escaped \*me
as declared in str1
, in the escaped str0
?