Skip to content

Instantly share code, notes, and snippets.

@zb3
Last active August 29, 2015 14:25
Show Gist options
  • Save zb3/57a8751e829a5af228be to your computer and use it in GitHub Desktop.
Save zb3/57a8751e829a5af228be to your computer and use it in GitHub Desktop.
Replace multiple strings with other strings in parallel in JS
/*
* search and replace are arrays (btw string is an array of characters)
* replaceParallel('ab', 'ba', 'abc') -> bac
* replaceParallel(['123', '2', '3', 'a'], ['2', '123', 'a', '3'], '1232322ac3') -> 2123a1231233ca
* Note: order matters if one search string begins with another
*/
function replaceParallel(search, replace, str) {
var t, ret = '', replaced = false, cursor = 0;
while (cursor<str.length) {
replaced = false;
for (t=0;t<search.length;t++) {
if (str.substr(cursor, search[t].length)===search[t]) {
replaced = true;
ret += replace[t];
cursor += search[t].length;
break;
}
}
if (!replaced)
ret += str[cursor++];
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment