views:

47

answers:

2

I have a string that looks something like this:

{theField} > YEAR (today, -3) || {theField}  < YEAR (today, +3)

I want it to be replaced into:

{theField} > " + YEAR (today, -3) + " || {theField}  < " + YEAR (today, +3) + "

I have tried this:

String.replace(/(.*)(YEAR|MONTH|WEEK|DAY+)(.*[)]+)/g, "$1 \" + $2 $3 + \"")

But that gives me:

{theField} > YEAR (today, +3) || {theField}  >  " + YEAR  (today, +3) + "

Does anyone have any ideas?

+1  A: 

You should be careful using greedy matching when you have .*. Usually this doesn't do what you want - it matches as much of the string as possible. You either need to use a negative character class to stop matching when you reach a certain character (e.g. [^)]) or else use a lazy match .*?. Here is how you could do it using the lazy quantifier:

s = '{theField} > YEAR (today, -3) || {theField}  < YEAR (today, +3)';
result = s.replace(/((YEAR|MONTH|WEEK|DAY).*?\))/g, '" + $1 + "')

Result:

{theField} > " + YEAR (today, -3) + " || {theField}  < " + YEAR (today, +3) + "

Note that I've cleaned up a bit in your regular expression:

  • Removed the + from DAY+ as KennyTM noted
  • Changed [)]+ to \)
  • Changed the literal replacement string from double-quoted to single-quoted so that the quotes in the replacement text don't need to be escaped
  • Removed the extra space you were putting into the result between YEAR and the following opening parenthesis
Mark Byers
A: 

Thank you Mark!

It worked perfectly so to night I might be able to go to sleep before 2:am (and with all my hair still attached to my head) :-)

OrjanL