Posted By

jatkins on 01/19/11


Tagged

regex search text match RegularExpression searching


Versions (?)

Global regex search


 / Published in: JavaScript
 

Released into the public domain. needle must be a regex; to pass a string, escape it and pass as new RegExp(escaped_string, 'g'). Case sensitive.

  1. function global_search(needle, haystack) {
  2. if(typeof needle=='function') {
  3. haystack_remaining = haystack;
  4. match = '';
  5. matches = [];
  6. results = [];
  7. result = 0;
  8. offset = 0;
  9. var i = 0;
  10. while(haystack_remaining && (result = haystack_remaining.search(needle)) != -1) {
  11. match = haystack_remaining.match(needle);
  12. match = match[0];
  13. matches[matches.length] = match;
  14. results[results.length] = result + offset;
  15. haystack_remaining = haystack_remaining.substring(result + match.length);
  16. offset += result + match.length;
  17. i++;
  18. }
  19. return [results, matches];
  20. }
  21. else
  22. return false;
  23. }

Report this snippet  

You need to login to post a comment.