2

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?

0

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that was a very delightful response. I'll have to register so I can upvote!
1

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, "+'");

Comments

0

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...

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.