Skip to content

Instantly share code, notes, and snippets.

@mojavelinux
Last active April 7, 2017 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mojavelinux/2cebc5fd0d2139715f7723f31ba5bfdd to your computer and use it in GitHub Desktop.
Save mojavelinux/2cebc5fd0d2139715f7723f31ba5bfdd to your computer and use it in GitHub Desktop.
A polyfill for the JavaScript String#replace function that uses undefined instead of empty string for non-participating groups. See http://blog.stevenlevithan.com/archives/npcg-javascript
if ('a'.replace(/(z)|./, function(match, g1) { return typeof g1; }) !== 'undefined') {
String.prototype.replace = (function (native_method) {
return function (pattern, callback) {
if (pattern.constructor.name !== 'RegExp' || typeof callback !== 'function') {
return native_method.call(this, pattern, callback);
}
var result = '', source = String(this), length = source.length, lastIndex = 0, index, match;
pattern.lastIndex = 0;
while ((match = pattern.exec(source))) {
index = match.index;
result += source.slice(lastIndex, index);
lastIndex = index + match[0].length;
match.push(index, source);
result += callback.apply(null, match);
pattern.lastIndex = lastIndex;
if (!pattern.global) break;
if (lastIndex === index) {
if (lastIndex === length) break;
pattern.lastIndex = lastIndex++;
result += source.charAt(lastIndex);
}
}
if (lastIndex < length) result += source.slice(lastIndex, length);
return result;
}
}(String.prototype.replace));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment