Does anyone have an existing, proven javascript method that will convert a plain text string to its equivalent regex string, with escapes ('\' added for all of the regex control characters?
Asked
Active
Viewed 351 times
1 Answers
1
This is a very common overlooked problem. I hope this routine helps.
/** add escapes for regexp special characters to turn plainText into a verbatim regexp string
*
* @param plainText plain text string that may contain characters that need to be escaped to become a regexp
* @returns {string} modified string that will work within a regexp
*/
regexpEscape: function (plainText) {
//noinspection JSLint
return plainText.replace(/([-()\[\]{}+?*.$\^|,:#<!\/\\])/g, '\\$1');
},

bret
- 796
- 9
- 5
-
That's exactly what I'm looking for; you are such a genius. I'll try it out and hopefully it will fill the bill. – user3233603 Jan 24 '14 at 21:25
-
1you can shorten your pattern with: `text.replace(/(?=[()[{+?*.^$|\\])/g, '\\')` (note: all other characters don't need to be escaped) – Casimir et Hippolyte Jan 24 '14 at 21:30
-
You must add the delimiter to the class: `\/` – Casimir et Hippolyte Jan 24 '14 at 21:48
-
plainText.replace(/([-()\[\]{}+?*.$\^|,:#<!\/\\])/g, '\\$1') – user3233603 Jan 24 '14 at 22:36
-
edited as per comments. Thank you. – bret Jan 24 '14 at 23:27