Posted By

cochambre on 08/02/06


Tagged

escape replace pattern text match regular expressions precompile speed


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

nicolaspar


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


 / Published in: JavaScript
 

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

  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  

You need to login to post a comment.