Permalink
Browse files

Override String#replace method

  • Loading branch information...
1 parent eaf4c85 commit 1370c5f3f490eeb9b3a47a63b95fa3c07f12c590 @Daniel15 committed Oct 1, 2012
Showing with 28 additions and 2 deletions.
  1. +18 −2 NamedRegExp.js
  2. +10 −0 NamedRegExp.spec.js
View
@@ -73,13 +73,29 @@
NamedRegExp.replace = function replace(string, pattern, replacement) {
if (typeof(replacement) !== 'function') {
// Switch the named backreferences with their index
- var replacement = replacement.replace(backref, function (match, name) {
+
+ var replacement = nativeReplace.call(replacement, backref, function (match, name) {
return '$' + pattern.namedGroupIndices[name];
});
}
- return string.replace(pattern, replacement);
+ return nativeReplace.call(string, pattern, replacement);
}
+ /**
+ * Override native String#replace method.
+ * Returns a new string with some or all matches of a `pattern`` replaced by a `replacement`.
+ * @param {RegExp|String} pattern Pattern to replace
+ * @param {String|Function} replacement What to replace `pattern` with
+ * @return {String} A new string with all the patterns replaced
+ */
+ nativeString.replace = function (pattern, replacement) {
+ // If we've got a NamedRegExp, use the replacement .replace function
+ if (pattern.isNamed)
+ return NamedRegExp.replace(this, pattern, replacement);
+ else
+ return nativeReplace.call(this, pattern, replacement);
+ };
+
return NamedRegExp;
})();
View
@@ -35,6 +35,16 @@ describe('NamedRegExp', function () {
expect(result).toBe(expected);
});
+ it('should function as a String method', function () {
+ var regexp = new NamedRegExp('^(?P<helloworld>\\d+)$');
+ var input = '12345';
+ var replacement = 'aaa \\k<helloworld> bbb';
+ var expected = 'aaa 12345 bbb';
+
+ var result = input.replace(regexp, replacement);
+ expect(result).toBe(expected);
+ });
+
it('should support replacing two groups', function () {
var regexp = new NamedRegExp('^(?P<year>\\d+) is (?P<msg>.+)$');
var input = '2012 is awesome';

0 comments on commit 1370c5f

Please sign in to comment.