Posted By

jatkins on 01/21/11


Tagged

regex replace text RegularExpression


Versions (?)

Replace multiple occurrences of a regex with replacements from an array


 / Published in: JavaScript
 

Released into the public domain. needle will be replaced needle.length times with the next chronological item from replacements. needle must be a regex (with the global modifier disabled); to pass a string, escape it and pass as new RegExp(escaped_string). Case sensitive. The commented out code below the main block is an earlier, unnecessarily more complicated version kept for reference.

  1. function find_replace(needle, haystack, replacements) {
  2. if(typeof needle == 'function' && !needle.global) {
  3. for(replacement in replacements) {
  4. haystack = haystack.replace(needle, replacements[replacement]);
  5. }
  6. return haystack;
  7. }
  8. else
  9. return false;
  10. }
  11.  
  12. /*function find_replace(needle, haystack, replacements) {
  13. if(typeof needle=='function') {
  14. haystack_remaining = haystack;
  15. match = '';
  16. result = 0;
  17. offset = 0;
  18. new_haystack = '';
  19. i = 0;
  20. while(haystack_remaining && (result = haystack_remaining.search(needle)) != -1) {
  21. match = haystack_remaining.match(needle);
  22. match = match[0];
  23. haystack_remaining = haystack_remaining.substring(result + match.length);
  24. new_haystack += haystack.substring(offset, result + offset) + replacements[i];
  25. offset += result + match.length;
  26. i++;
  27. }
  28. return new_haystack + haystack.substring(offset);
  29. }
  30. else
  31. return false;
  32. }*/

Report this snippet  

You need to login to post a comment.