Regular Expressions simple strings search/replace escape method (with RE speed enhancment - precompilation)


/ Published in: JavaScript
Save to your folder(s)

Usefull Regular Expressions enhancement. Simplifies standard string operations escaping special chars. And also saves precompiled REs for a speed increase.


Copy this code and paste it in your HTML
  1. RegExp.escape = function(text) {
  2. if (!arguments.callee.sRE) {
  3. var specials = [
  4. '/', '.', '*', '+', '?', '|',
  5. '(', ')', '[', ']', '{', '}', '\\\\'
  6. ];
  7. arguments.callee.sRE = new RegExp(
  8. '(\\\\' + specials.join('|\\\\') + ')', 'g'
  9. );
  10. }
  11. return text.replace(arguments.callee.sRE, '\\\\$1');
  12. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.