Method: replace()
replace() replaces the matched pattern or patterns in the string with a replacement string. It works very similarly to JavaScript's String.replace(regex, string|function).
Syntax
var exp = new apgExp(pattern[, flags]); var result = exp.replace(str, replacement);
Parameters
• str: string: The string to match pattern in.
• replacement: string/function
- string: The matched patterns are replaced with this string.
The string can contain the following special characters:
Pattern Inserts $$ Inserts the character "$". $` Inserts the portion of the string preceding the matched pattern. $& Inserts the matched pattern. $' Inserts the portion of the string following the matched pattern. ${name} Inserts the sub-string last matched by rule "name" or undefined if none. - function: A function with the prototype:
var func = function(result, exp){ var replacement; /* construct replacement possibly using the values */ /* in result and/or exp */ return replacement; }
Return
Returns a copy of str with the matched pattern or patterns replaced with replacement.
If the flags argument is absent or empty, only the first match in str is replaced. If flags is "g" or "y", all matches in str are replaced.
Example 1
The global flag is set, so all matches are replaced.
var pattern, str, exp, result; pattern = 'pattern = A / X\n'; pattern += 'A = "abc"\n'; pattern += 'X = "xyz"\n'; str = "---abc---xyz---ABC---XYZ---"; exp = new apgExp(pattern, "g"); result = exp.replace(str, "555"); console.log(" str: " + str); console.log("result: " + result); /* returns */ str: ---abc---xyz---ABC---XYZ--- result: ---555---555---555---555---
Example 2
The global flag is not set, so only the first match is replaced. The replacement string contains special characters indicating a replacement string of "$-|||-$" since ||| is the prefix ($`) to the match.
var pattern, str, exp, result; pattern = 'pattern = A / X\n'; pattern += 'A = "abc"\n'; pattern += 'X = "xyz"\n'; str = "|||abc---xyz---ABC---XYZ---"; exp = new apgExp(pattern, ""); result = exp.replace(str, "$$-$`-$$"); console.log(" str: " + str); console.log("result: " + result); /* returns */ str: |||abc---xyz---ABC---XYZ--- result: |||$-|||-$---xyz---ABC---XYZ---
Example 3
The replacement function will examine result and replace with "555" if rule A is matched or with "666" if rule X is matched.
var pattern, str, exp, result; var rfunc = function(result, exp){ var str = "???"; if(result.rules.A){ str = "555"; }else if(result.rules.X){ str = "666"; } return str; } pattern = 'pattern = A / X\n'; pattern += 'A = "abc"\n'; pattern += 'X = "xyz"\n'; str = "---abc---xyz---ABC---XYZ---"; exp = new apgExp(pattern, "g"); result = exp.replace(str, rfunc); console.log(" str: " + str); console.log("result: " + result); /* returns */ str: ---abc---xyz---ABC---XYZ--- result: ---555---666---555---666---