Escaping regular expression characters in an input string


When using input gathered from a user to create a regular expression, the user input may contain regular expression control characters such as ‘.’ and ‘*’. These need to be escaped so the regular expression engine treats them as literal characters.

Here’s on way to do it:

re = new RegExp(‘^’ + selection.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, “\\$&”) + ‘$’, ‘i’);

This is an example for Javascript. The example uses the option to pass the String.replace() method a regular expression containing an array of characters and prepends any with a leading backslash (that’s the “\\$&” sequence). The ‘g’lobal flag is used to ensure each occurrence is updated.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!