I'm working in a problem which require replace negative regex.
If I have a string text
, a regex pattern re
and a transform function f
I want to have a negativeReplace
function which replace all don't match sub strings with re
pattern in text
string by apply transform function f
, and remain the rest.
# input
var text = " aa ( bb ) cc ";
var re = /[\(].*?[\)]/g;
var f = function(s){ return s.toUpperCase() }
# expected output
negativeReplace(text, re, f)
# -> " AA ( bb ) CC "
Here is my best try so far
function negativeReplace(text, re, f){
var output = ""
var boundary = 0;
while((match = re.exec(text)) != null){
output += f(text.slice(boundary, match.index)) + match[0];
boundary = match.index + match[0].length;
}
output += f(text.slice(boundary, text.length));
return output;
}
It worked!
function negativeReplace(text, re, f){
var output = ""
var boundary = 0;
while((match = re.exec(text)) != null){
output += f(text.slice(boundary, match.index)) + match[0];
boundary = match.index + match[0].length;
}
output += f(text.slice(boundary, text.length));
return output;
}
var text1 = " aa ( bb ) cc ";
var text2 = " aa { bb } cc { dd } ee ";
var f1 = function(s){ return s.toUpperCase() }
var f2 = function(s){ return "_" + s + "_" }
re = /[\({].*?[\)}]/g
console.log(negativeReplace(text1, re, f1)) // AA ( bb ) CC
console.log(negativeReplace(text2, re, f1)) // AA { bb } CC { dd } EE
console.log(negativeReplace(text1, re, f2)) // _ aa _( bb )_ cc _
console.log(negativeReplace(text2, re, f2)) // _ aa _{ bb }_ cc _{ dd }_ ee
However, my implement seems too complicated. Because javascript already has replace
function with matched pattern. And with simple case of negative regex
like replace with a blank all characters except numbers, there is solution in this post.
So my question is how can I solve this problem better (can I use replace
for this, how can I improve my code).
Thank you so much.