Skip to content

Instantly share code, notes, and snippets.

@fuzzyfox
Created June 22, 2013 18:21
Show Gist options
  • Save fuzzyfox/5841963 to your computer and use it in GitHub Desktop.
Save fuzzyfox/5841963 to your computer and use it in GitHub Desktop.
JavaScript: preg_replace
/**
* preg_replace (from PHP) in JavaScript!
*
* This is basically a pattern replace. You can use a regex pattern to search and
* another for the replace. For more information see the PHP docs on the original
* function (http://php.net/manual/en/function.preg-replace.php), and for more on
* JavaScript flavour regex visit http://www.regular-expressions.info/javascript.html
*
* NOTE: Unlike the PHP version, this function only deals with string inputs. No arrays.
*
* @author William Duyck <[email protected]>
* @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License 2.0
*
* @param {String} pattern The pattern to search for.
* @param {String} replace The string to replace.
* @param {String} subject The string to search and replace.
* @param {Integer} limit The maximum possible replacements.
* @return {String} If matches are found, the new subject will be returned.
*/
var preg_replace = function(pattern, replace, subject, limit){
if(limit === undefined) {
limit = -1;
}
var _flag = pattern.substr(pattern.lastIndexOf(pattern[0])+1),
_pattern = pattern.substr(1, pattern.lastIndexOf(pattern[0])-1),
reg = new RegExp(_pattern, _flag),
rs = null,
res = [],
x = 0,
y = 0,
rtn = subject;
var tmp = [];
if(limit === -1){
do {
tmp = reg.exec(subject);
if(tmp !== null) {
res.push(tmp);
}
} while(tmp !== null && _flag.indexOf('g') !== -1);
}
else {
res.push(reg.exec(subject));
}
for(x = res.length -1; x > -1; x--){
tmp = replace;
for(y = res[x].length; y > -1; y--){
tmp = tmp.replace('${' + y + '}', res[x][y])
.replace('$' + y, res[x][y])
.replace('\\' + y, res[x][y]);
}
rtn = rtn.replace(res[x][0], tmp);
}
return rtn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment