Skip to content

Instantly share code, notes, and snippets.

@firegurafiku
Last active December 12, 2015 01:59
Show Gist options
  • Save firegurafiku/4695352 to your computer and use it in GitHub Desktop.
Save firegurafiku/4695352 to your computer and use it in GitHub Desktop.

JavaScript snippets

This gist contains snippets code in JavaScript, one snippet per file. Files here should be name after functions they contain, functions should have short descriptive comments in front of their bodies and the link to there they are taken from (if any) or copyright notice.

/**
* Perform simultaneous multiple replaces in given string.
* Usage example:
* @code
* MultipleReplace("1 2 3 4", [
* [/1/, '2'],
* [/2/, '3'],
* [/3/, '4']]);
* // Returns: "2 3 4 4"
* @endcode
*
* @note
* 1. Global qualifier (@c /g) is not supported.
* 2. Patterns order does matter. First items will have
* priority when several regexes match same substring.
*
* @author Pavel Kretov <firegurafiku@gmail.com>
* @copyright MIT License
*/
function MultipleReplace(str, replacements)
{
var result = "";
var rest = str;
while (rest != "")
{
var closestMatch = null;
var closestIdx;
for (var idx = 0; idx < replacements.length; ++idx)
{
var rex = replacements[idx][0];
var repl = replacements[idx][1];
var match = rex.exec(rest);
if (match && match.index >= 0)
{
if (!closestMatch || match.index < closestMatch.index)
{
closestMatch = match;
closestIdx = idx;
}
}
}
if (!closestMatch)
{
result += rest;
rest = "";
}
else
{
var matchIndex = closestMatch.index;
var matchLength = closestMatch[0].length;
result += rest.substr(0, matchIndex);
result += closestMatch[0].replace(
replacements[closestIdx][0],
replacements[closestIdx][1]);
rest = rest.substr(matchIndex + matchLength);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment