Last active
April 7, 2017 02:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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