/ 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.
Expand |
Embed | Plain Text
function find_replace(needle, haystack, replacements) { if(typeof needle == 'function' && !needle.global) { for(replacement in replacements) { haystack = haystack.replace(needle, replacements[replacement]); } return haystack; } else return false; } /*function find_replace(needle, haystack, replacements) { if(typeof needle=='function') { haystack_remaining = haystack; match = ''; result = 0; offset = 0; new_haystack = ''; i = 0; while(haystack_remaining && (result = haystack_remaining.search(needle)) != -1) { match = haystack_remaining.match(needle); match = match[0]; haystack_remaining = haystack_remaining.substring(result + match.length); new_haystack += haystack.substring(offset, result + offset) + replacements[i]; offset += result + match.length; i++; } return new_haystack + haystack.substring(offset); } else return false; }*/
You need to login to post a comment.
