Post by Chris on Feb 17, 2020 3:47:46 GMT -8
You can implement your own custom lookahead/lookbehind in other browsers by using the function form of replace:
This can be used to for example exempt matches contained within code tags, preceded by an equal sign, etc.
sourceText.replace(/blah/, function(matchedText, parentheticalCaptures, sourceText, sourceIndex){
//examine sourceText here for what preceded matchedText as well as what is yet to come then return replacement text based on decision.
})
This can be used to for example exempt matches contained within code tags, preceded by an equal sign, etc.
Correction:
elli my apologies, I should have verified before hitting that post button! I gave you the wrong order for the expected function parametersSpecifying a function as a parameter
You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
The arguments to the function are as follows:
Possible name | Supplied value |
match | The matched substring. (Corresponds to $& above.) |
p1, p2, ... | The nth string found by a parenthesized capture group, provided the first argument to replace() was a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+. |
offset | The offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) |
string | The whole string being examined. |
(The exact number of arguments will depend on whether the first argument was a RegExp object and, if so, how many parenthesized submatches it specifies.)
The following example will set newString to 'abc - 12345 - #$*%':
function replacer(match, p1, p2, p3, offset, string) {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%