I'm performing this on a string:
var poo = poo
.replace(/[%][<]/g, "'<")
.replace(/[>][%]/g, ">'")
.replace(/[%]\s*[+]/g, "'+")
.replace(/[+]\s*[%]/g, "+'");
Given the similar if these statements, can these regexs be comebined somehow?
I'm performing this on a string:
var poo = poo
.replace(/[%][<]/g, "'<")
.replace(/[>][%]/g, ">'")
.replace(/[%]\s*[+]/g, "'+")
.replace(/[+]\s*[%]/g, "+'");
Given the similar if these statements, can these regexs be comebined somehow?
No, I don't think so. At least, I suspect for any transformation involving fewer replaces I can come up with a string that your original and the proposed alternative treat differently. However, it may be that the text you're working with wouldn't trigger the differences, and so for practical purposes a shorter transformation would work as well. Depends on the text.
You can simplify it a little bit. You don't need all the range syntax
poo
.replace(/%</g, "'<")
.replace(/>%/g, ">'")
.replace(/%\s*\+/g, "'+")
.replace(/\+\s*%/g, "+'");
Since in either case, the replacement only turns %
into '
and removes spaces:
var poo = 'some annoying %< string >% with some % + text + %';
poo = poo.replace(/%<|>%|%\s*\+|\+\s*%/g, function(match) {
return match.replace('%', '\'').replace(/\s/g,'');
});
// "some annoying '< string >' with some ' + text + '"
Although that's not much simpler...
Using lookahead assertions and capturing:
var poo = poo.replace(/%(?=<)|(>)%|%\s*(?=\+)|(\+)\s*%/g, "$1$2'");
Using capturing alone:
var poo = poo.replace(/(>)%|(\+)\s*%|%(<)|%\s*(\+)/g, "$1$2'$3$4");
If JS's RegExp supported lookbehind assertions:
var poo = poo.replace(/%(?=<)|(?<=>)%|%\s*(?=\+)|(?<=\+)\s*%/g, "'");
but it doesn't.