Monday 15 August 2011

.NET's Match.Result in javascript -



.NET's Match.Result in javascript -

is there equivalent match.result .net in javascript using replace function, 1 can still utilize convenient substitutions perhaps part of logic?

or 1 need provide custom yet simple function next seems work in cases?

regexp.matchresult = function (subexp, offset, str, matches) { homecoming subexp.replace(/\$(\$|&|`|\'|[0-9]+)/g, function (m, p) { if (p === '$') homecoming '$'; if (p === '`') homecoming str.slice(0, offset); if (p === '\'') homecoming str.slice(offset + matches[0].length); if (p === '&' || parseint(p, 10) <= 0 || parseint(p, 10) >= matches.length) homecoming matches[0]; homecoming matches[parseint(p, 10)]; }); }; var subexp; //fill in substitution look var replacefunc = function () { homecoming regexp.matchresult(subexp, arguments[arguments.length - 2], arguments[arguments.length - 1], array.prototype.slice.call(arguments).slice(0, -2)); };

your function looks nice, can think of different way:

class="snippet-code-js lang-js prettyprint-override">string.prototype.replacematch = function(re, replacement, fn) { fn = fn || function(p) { homecoming p; }; homecoming this.replace(re, function(m) { var replaced = m.replace(re, replacement); var params = array.prototype.slice.call(arguments); params.unshift(replaced); homecoming fn.apply(this, params); }); }; // simple illustration alert("foo 42 bar 12345 baz".replacematch( /(\d)(\d*)/g, "[$1]($2)", function(replaced, m, a, b) { homecoming replaced + "<" + + "," + b + ">"; } ));

there's gotcha: work if regex can match result of match, it's not applicable cases. (i realized after writing answer)

and don't know if qualifies simpler yours though...

javascript .net regex

No comments:

Post a Comment